Search code examples
c++c++11vectortemporary-objects

How to get rid of (one) unnecessary copy when constructing a vector?


I have a class A which handles my resources (quite large). Now I need a vector of these std::vector<A> vec_of_A (3, A(int N)). Problem is that vector first constructs temporary object A(int N), then copy constructs from that three times and then destroys that temporary object. As my A(int N) allocates quite a large chunk of memory I end up (temporarily) with memory requirements 33% larger than I actually need.

How to construct vector of A while avoiding unnecessary constructors? (My class A satisfies all rules of five).

EDIT: Sorry I didn't realize the importance of default constructed object A. My question is not about default constructor but parametrizied constructor.


Solution

  • If you just want to default construct the objects in the vector you can just use

    std::vector<A> vec_of_A(some_number);
    

    That will create some_number default items.

    If the items are not default constructable then reserve the space that you need and then use emplace_back to constructs the elements in place. that looks like

    std::vector<A> vec_of_A;
    vec_of_A.reserve(some_number);
    for (int i = 0; i < some_number; ++i)
        vec_of_A.emplace_back(/*constructor parameter(s) here */); // construct an object