Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor not called when returning a local instance [duplicate]

Possible Duplicate:
Why is the destructor not called for the returned object from the function?

I wrote some C++ code (below), compiled it with GCC 4.6 and it ran successfully. But I don't know why the destructor of classA isn't called when returning from createA().

Since ca is a local variable in createA() (i.e. on the stack), I think its destructor should be called when returning from the function. But in fact, the destructor is only called once when returning from the main function.

Moreover, returning a local instance always works fine in this test. I wonder if it's safe to return a local instance on a stack frame when the frame has been popped out after returning.

This is my code:

#include <iostream>
#include <string.h>

class classA
{
public:
    classA() { len = 0; v = 0; }

    classA(int a)
    {
        len = a;
        v = new int[a];
        for (int i = 0; i < a; i++)
            v[i] = 2*i;
    }

    ~classA()
    {
        if (v)
            {
            memset(v, 0, len * sizeof(int));
            delete [] v;
        }
    }

    int *v;
    int len;
};

classA createA(int a)
{
    classA ca(a);
    return ca;
}

using namespace std;

int main()
{
    int a = 10;
    classA ca = createA(a);
    classA *pca = &ca;
    for (int i = 0; i < a; i++)
        cout << pca->v[i];
    cout << endl;
    return 0;
}
like image 567
Yantao Xie Avatar asked Jun 18 '12 06:06

Yantao Xie


1 Answers

This is called return value optimization.

In short, the compiler doesn't have to return a copy of the object to optimize the code.

For ca is a local variable, i.e. on the stack [...]

Not necessarily. ca can be created directly in the calling context to prevent the extra copy. Copy elision is the only optimization that a compiler is free to perform that can alter expected behavior.

like image 125
Luchian Grigore Avatar answered Sep 30 '22 16:09

Luchian Grigore