Linked Questions

Popular Questions

Copy constructor when adding an element to vector

Asked by At

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
    int x;
    foo() {}
    foo(int bar) : x(bar) {}

int main()
    std::vector<std::shared_ptr<foo>> foos;
    auto n = std::make_shared<foo>(42);

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


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, 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));?

Related Questions