Iterating over a container of unique_ptr’s

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.

Leave a Comment