Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor is called on unwanted object during assignment

myClassVar = MyClass(3);  

I expected destructor being called on the previously created myClassVar on the left.
But it is actually being called on the new object that's created by MyClass(3).

My full test code and output follows..

edit

How do I fix the problem?
Implement an assignment operator?
MyClass actually has pointers, and MYSQL_STMT*, I wonder how should I deal with MYSQL_STMT* variable.

I just need MyClassVar(3) object not the MyClassVar() which was first created when ClientClass object was created.

I came across this situation fairly often, and wonder if there's a good way to do it.

#include <stdio.h>

class MyClass
{
public:
    MyClass() { printf("MyClass %p\n", this); }
    MyClass(int a) { printf("Myclass(int) %p\n", this); }
    ~MyClass() { printf("~MyClass %p\n", this); }

private:
    int mA;
};


class ClientClass
{
public:
    void Foo()
    {
        printf("before &myClassVar : %p\n", &myClassVar);
        myClassVar = MyClass(3); // this is the important line
        printf("after &myClassVar : %p\n", &myClassVar);
    }

private:
    MyClass myClassVar;
};

int main()
{   
    ClientClass c;
    c.Foo();
    return 0;
}

MyClass 0x7fff5fbfeba0
before &myClassVar : 0x7fff5fbfeba0
Myclass(int) 0x7fff5fbfeb70
~MyClass 0x7fff5fbfeb70 // <--- here destructor is called on the newly created object
after &myClassVar : 0x7fff5fbfeba0
~MyClass 0x7fff5fbfeba0
like image 580
eugene Avatar asked Oct 28 '11 06:10

eugene


1 Answers

Here's how the critical line breaks down:

myClassVar = MyClass(3);

First, MyClass(3) calls constructor and returns the object.

Second, myClassVar = copies the object to myClassVar.

Then the statement ends. The object (which is an immediate) is dead, and thus the destructor is invoked.

EDIT :

As for how to get around this. The only way I can think of is to use a placement new. I'm not sure if there's a better solution other than making a "set" method.

like image 184
Mysticial Avatar answered Oct 12 '22 09:10

Mysticial