I was wandering - can I use std::shared_ptr
as a map key?
more specifically - the reference counter of the pointer might be different from the value it had when assigned to the map.
Will it be correctly identified in the map?
So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object. When to use shared_ptr? Use shared_ptr if you want to share ownership of a resource.
A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.
By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).
The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.
Yes you can. std::shared_ptr
has operator<
defined in a way appropriate for map key usage. Specifically, only pointer values are compared, not reference counts.
Obviously, the pointed objects are not part of the comparison. Otherwise one could easily make the map invalid by modifying a pointed object and making the order in the map inconsistent with the comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With