0

Following program C++ compiled using g++ -O0 a.cpp -std=c++98:

class A
{
public:
        A(const A& a)  { cout << "A copy" << endl; }
        A() { cout << "A" << endl; }
        ~A() {cout << "~A" << endl; }
};

A f()
{
        cout << "f1" << endl;
        A a1;
        cout << "f2" << endl;
        return a1;
}

int main()
{
        cout << "m1" << endl;
        A a2 = f();
        cout << "m2" << endl;
}

Produces output:

m1
f1
A
f2
m2
~A

What bothers me is that after f2 the destructor and copy constructors are not called. From my understanding a1 goes out of scope and its destructor must be called. It looks like the object is moved from local a1 to a2 without copying. I understand that there is return value optimization but it is optimization and optimization must not change the logic of code and there is missing output saying ~A and A copy.

Trismegistos
  • 3,821
  • 2
  • 24
  • 41

0 Answers0