Search code examples
c++movecopy-constructor

Copy constructor when adding an element to vector


When we create an object and assign it to a variable and then we want to add it to some container, let's say std::vector, two things happen:

  • the constructor is called for creating an object earlier
  • the copy constructor is called when doing push_back

When we don't need the object anymore, we can use std::move, to speed the process up. So let's say I have a code like this:

#include <vector>
#include <cstdio>
#include <memory>

class foo
{
public:
    int x;
    foo() {}
    foo(int bar) : x(bar) {}
};

int main()
{
    std::vector<std::shared_ptr<foo>> foos;
    auto n = std::make_shared<foo>(42);
    foos.push_back(std::move(n));
}

But what if I didn't define the variable? What if I just did:

foos.push_back(std::make_shared<foo>(42));

Is the copy constructor invoked then? Should I use std::move? (like foos.push_back(std::move(std::make_shared<foo>(42)));) I tried to check it under godbolt.org, but I cannot see anything in the assembler mess. So is there a copy constructor invoked (so I would use std::move to eliminate that) or it is not, and should I leave it like this: foos.push_back(std::make_shared<foo>(42));?


Solution

  • Well if you are not going to use it after creating you can directly add it directly ( cause it will construct the object in place)

    foos.emplace_back(std::make_shared<foo>(42));
    

    (push_back will create a temporary & then copy it so extra copy)