I would like to know why an element I push back into a vector gets its destructor called in this situation:
#include <iostream>
#include <vector>
class Foo
{
public:
Foo(int a)
: m_a(a)
{
std::cout << "Foo ctor() " << m_a << std::endl;
}
~Foo()
{
std::cout << "Foo dtor() " << m_a << std::endl;
}
private:
int m_a;
};
class FooStorage
{
public:
static void createFoo(int a)
{
m_foos.push_back(Foo(a));
}
static std::vector<Foo> m_foos;
};
std::vector<Foo> FooStorage::m_foos;
int main()
{
std::cout << "Before: " << FooStorage::m_foos.size() << std::endl;
FooStorage::createFoo(53);
std::cout << "After: " << FooStorage::m_foos.size() << std::endl;
return 0;
}
This prints out the following:
Before: 0
Foo ctor() 53
Foo dtor() 53
After: 1
Foo dtor() 53
I'd like to know:
- What gets deleted? (inbetween the 'Before' and 'After' couts)
- Why does it get deleted?
- What ends up in the vector?