I'm trying to understand object lifetime in C++. When I run the code:
class Foo
{
public:
Foo();
Foo(const Foo &old);
~Foo();
int x_;
};
int nextX = 0;
Foo::Foo()
{
cout << "Foo(): " << (x_ = nextX++) << endl;
}
Foo::Foo(const Foo &old)
{
cout << "Foo(const Foo &old): " << (x_ = nextX++) << endl;
}
Foo::~Foo()
{
cout << "~Foo(): "<< x_ << endl;
}
int main()
{
Foo foo;
cout << "-----------------" << endl;
vector<Foo> v(1);
cout << "-----------------" << endl;
Foo bar;
cout << "-----------------" << endl;
v[0]=bar;
cout << "-----------------" << endl;
return 0;
}
I get the following output:
Foo(): 0
-----------------
Foo(): 1
-----------------
Foo(): 2
-----------------
-----------------
~Foo(): 2
~Foo(): 2
~Foo(): 0
So, my questions are:
- Why the copy constructor is not called in the statement
v[0]=bar
? - Why the destructor for the object originally called bar is called twice (i.e.
~Foo(): 2
is seen twice on the output)?
Would anyone be able to help me, please?
Thank you