Iterating over a container of unique_ptr's

Dr DR picture Dr DR · Nov 23, 2011 · Viewed 27.5k times · Source

How does one access unique_ptr elements of a container (via an iterator) without taking ownership away from the container? When one gets an iterator to an element in the container is the element ownership still with the container? How about when one dereferences the iterator to gain access to the unique_ptr? Does that perform an implicit move of the unique_ptr?

I find I'm using shared_ptr a lot when I need to store elements in a container (not by value), even if the container conceptually owns the elements and other code simply wishes to manipulate elements in the container, because I'm afraid of not being able to actually access the unique_ptr elements in the container without ownership being taken from it.

Any insights?

Answer

Pascal picture Pascal · Dec 1, 2014

With auto and the range-based for-loops of C++11 this becomes relatively elegant:

std::vector< std::unique_ptr< YourClass >> pointers;
for( auto&& pointer : pointers ) {
    pointer->functionOfYourClass();
}

The reference & to the std::unique_ptr avoids the copying and you can use the uniqe_ptr without dereferencing.