-1

kind of a silly question but I have a metaphysical doubt which is why I need to ask.

When pushing back an object to a vector, assuming I do not need to update the object beforehand, can I avoid the usage of a local variable ?

void addToVector(std::vector<Foo>& fooVector)
{
    // Solution #1
    Foo foo;
    fooVector.push_back(foo);
    // Solution #2
    fooVector.push_back(Foo());
}

Would solution #2 leak memory knowing that there is no local variable going out-of-scope encapsulating Foo ?

Assuming solution #2 is valid, is it more efficient than solution #1 ? (emplace_back would probably be, but I'm still stuck with c++03)

codeJack
  • 2,423
  • 5
  • 24
  • 31
  • 2
    In general terms, they are equivalent. The first constructs a named variable that is copied into the vector, and destroyed when it passes out of scope. The second constructs am unnamed temporary that is copied into the vector, and destructed at the end of the statement. – Peter Jan 10 '17 at 10:06
  • Perfect answer, thanks – codeJack Jan 10 '17 at 10:10

1 Answers1

2

push_back copies the item into the vector, so as you say emplace_back would be most efficient.

Your use of the temporary Foo() doesn't leak.

doctorlove
  • 18,872
  • 2
  • 46
  • 62