I'm trying to fill a std::vector
with objects created in a function like so:
class Foo
{
public:
Foo() { std::cout << "Foo created!\n"; }
Foo(const Foo& other) { std::cout << "Foo copied!\n"; }
Foo(Foo&& other) { std::cout << "Foo moved\n"; }
~Foo() { std::cout << "Foo destroyed\n"; }
};
static Foo createFoo()
{
return Foo();
}
int main()
{
{
std::vector<Foo> fooVector;
fooVector.reserve(2);
fooVector.push_back(createFoo());
fooVector.push_back(createFoo());
std::cout << "reaching end of scope\n";
}
std::cin.get();
}
Output:
Foo created!
Foo moved
Foo destroyed
Foo created!
Foo moved
Foo destroyed
reaching end of scope
Foo destroyed
Foo destroyed
How can Foo
be destroyed more times than it is created? I don't understand what is happening here, I thought that Foo
would be copied, but the copy constructor is not triggered.
What is the best way to fill a std::vector
with objects created elsewhere without them being destroyed?