How to store objects without copy or move constructor in std::vector?

For the start, std::mutex can not be copied or moved, therefore you are forced to use some kind of indirection.

Since you want to store mutex in a vector, and not copy it, I would use std::unique_ptr.

vector<unique_ptr<T>> does not allow certain vector operations (such as for_each)

I am not sure I understand that sentence. It is perfectly possible to do range for :

std::vector< std::unique_ptr< int > > v;
// fill in the vector
for ( auto & it : v )
  std::cout << *it << std::endl;

or to use std algorithms :

#include <iostream>
#include <typeinfo>
#include <vector>
#include <memory>
#include <algorithm>


int main()
{
    std::vector< std::unique_ptr< int > > v;
    v.emplace_back( new int( 3 ) );
    v.emplace_back( new int( 5 ) );
    std::for_each( v.begin(), v.end(), []( const std::unique_ptr< int > & it ){ std::cout << *it << std::endl; } );
}

Leave a Comment