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

前端 未结 4 464
情书的邮戳
情书的邮戳 2021-02-01 16:58

To improve efficiency of std::vector, it\'s underlying array needs to be pre-allocated and sometimes re-allocated. That, however, requires the creation and

4条回答
  •  盖世英雄少女心
    2021-02-01 17:13

    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> 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 
    #include 
    #include 
    #include 
    #include 
    
    
    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; } );
    }
    

提交回复
热议问题