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

前端 未结 4 476
情书的邮戳
情书的邮戳 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:20

    That requires however the creation of objects of type T with a copy ctor.

    That is not entirely right, as of C++11, if you use the constructor of std::vector which will default construct a number of elements, then you don't need to have a copy or move constructor.

    As such, if no threads are added or deleted from your pool, you can then just do:

    int num = 23;
    std::vector vec(num);
    

    If you want to add or delete things dynamically, then you have to use an indirection.

    1. Use std::vector + std::unique_ptr as already proposed
    2. Use a std::deque, that allows you to neatly use it with range based for loops or std-algorithms and avoids all indirections. (Which only allows additions)
    3. Use a std::list/forward_list this solution is similar to number one, however it has the additional benefit of easier usage with range based for and algorithms. It's probably the best if you are only accessing the elements sequentially as there is no support for random-access.

    Like this:

    std::deque deq;
    deq.emplace_back();
    deq.emplace_back();
    
    for(auto& m : deq) {
        m.lock();
    }
    

    As a final note, std::thread is of course moveable, so you can use std::vector + std::vector::emplace_back with it.

提交回复
热议问题