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:
v[0]=bar
?~Foo(): 2
is seen twice on the output)?Would anyone be able to help me, please?
Thank you
The assignment operator is called because the object at v[0] has already been constructed. The automatic assignment operator will perform a shallow copy of all members which ...
Because of the shallow copy of the automatic assignment operator it will appear that the ~Foo(): 2 is seen twice since two objects contain the member _x with a value 2.