Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std shared_ptr as std::map key

Tags:

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?

like image 404
sara Avatar asked Jun 16 '14 08:06

sara


People also ask

When should you use shared_ptr?

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.

What does shared_ptr get () do?

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.

What happens when you move a shared_ptr?

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).

Can you copy a shared_ptr?

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.


1 Answers

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.

like image 103
Wojtek Surowka Avatar answered Oct 19 '22 22:10

Wojtek Surowka