0

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

  • 1
    `v[0]=bar` is not copy construction, but assignment (which you have not overloaded). (And this is *soo much* a duplicate.) – Bo Persson Nov 09 '15 at 21:05
  • First I would say that you're going to need to make "nextX" a static variable so that it doesn't get reset to 0 for each new object. See what happens from there. – BCza Nov 09 '15 at 21:05
  • Polka Dancer nextX is not in the class so won't reset, it is global and static already. – Tim Beaudet Nov 09 '15 at 21:06

3 Answers3

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

Tim Beaudet
  • 791
  • 7
  • 16
1

At v[0]=bar; an implicitly defined copy assignment operator (Foo &operator=(const Foo &);) is called. It copies x_ (2) from bar to v[0]. So, you see 2 when destructors of bar and v[0] are called.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

Try the assignment operator is being used and hence 2 appearing twice

Ed Heal
  • 59,252
  • 17
  • 87
  • 127