1

Trying to understand why my destructor get invoked only twice in the following example:

#include <iostream>
#include <vector>
using namespace std;

class myclass{
public:
    int a, b, c;
    vector<int> mvec;
    ~myclass(){
        cout << "getting destroyed ...\n";
    }
};

myclass factory_method(){
    myclass a {9,99,999, {0,1,2,3}};
    //cout << a;
    return a;
}

void test_func(){
    cout << "====\n";
    myclass b = factory_method();
    myclass c {b};
}

int main (){
    test_func();
    return 0;
}

// prints the following
//====
//getting destroyed ...
//getting destroyed ...

As I understand, the compiler generates copy/move constructors and assignment functions, which I can see working.

But in this piece of code I'm creating 3 objects, 1 in factory_method on stack (which is moved and I understand that). This object a will be destroyed when its stack frame is destroyed, then in test_func, object b is moved to, from factory_method and object c is created by compiler generated copy constructor on object b. Both object b and c should get destroyed when test_func stack frame gets destroyed and I should see 3 'getting destroyed' messages.

I get only two, am I missing something? Can someone please explain?

Thank you!

pranav3688
  • 694
  • 1
  • 11
  • 20
  • 4
    The compiler is doing optional copy-elision here. If you turn that off you get 3 destructor [calls](https://godbolt.org/z/Eo9nqW). – cigien Oct 25 '20 at 22:27
  • 2
    See return value optimization – MrTux Oct 25 '20 at 22:27
  • @cigien : thank you! and special thanks for the link to godbolt.org, a new tool for me to explore! :) – pranav3688 Oct 25 '20 at 22:31
  • 1
    You're welcome :) It's a lot of fun, and you can play with lots of settings, like different compilers/ versions/ etc... :) – cigien Oct 25 '20 at 22:32

0 Answers0