Search code examples
c++object-lifetime

C++ object lifetime and destructors called


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:

  1. Why the copy constructor is not called in the statement v[0]=bar?
  2. 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


Solution

    1. 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 ...

    2. 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.