# destructor

## Recommended Posts

Hi: This question maybe is very pool. But I hope you can help me. Today, I just tested some trivial questions with c++. I found destructor is called after the assignment symbol. So ,I want to ask the object which come out by copy constructor is destructed after the the operation of assignment symbol finished? thank you very much

##### Share on other sites
The destructor is called when an object is destroyed. There are cases when this can happen immediatley after an assignment, but the assignment actually has nothing to do with the destructor being called.

class a{public:    a(int v) : val(v) { }    a(const a &v) : val(v.val) { }    int val;};void f(){    a x=a(20);}

It is possible that after the assignment in f() above, the temporary a object on the right hand side of the assignment will be destroyed, in which case the destructor will be called.

Equally, at the end of the function, when the a object x goes out of scope, its destructor will be called.

##### Share on other sites
Your question was extremly unclear. Since I can't understand what you were asking, I'll simply explain the descructor since your question seems to have to do with when that is called.

The destructor is called whenever the object is destroyed. For local variables, this could be when they go out of scope, or when objects created on the free store (with the new operator) are deleted (with the delete operator. Here is an example:

MyClass *mc = new MyClass; //Constructor is calleddelete mc; //destructor is calledvoid func(){    MyClass mc2;//constructor is called}//destructor is called

##### Share on other sites
What might be happening is that a temporary is being destroyed. Take the following for example:

class MyClass{public:    MyClass() { std::cout << "Constructor" << std::endl; }    ~MyClass() { std::cout << "Destructor" << std::endl; }    void DoStuff() { std::cout << "Doing stuff" << std::endl; }};MyClass func(){    MyClass result;    return result;}int main(){    MyClass myClass = func();}

What can happen here is up to 3 instances of MyClass could be created and destroyed. The first created is 'result' inside of 'func(), a temporary copy is then created when returning 'result' and the original 'result' is destroyed, myClass is then copy constructed and the temporary destroyed, and finally 'myClass' is destroyed when 'main()' exits.

....I say 'up to 3 instances' because under the right circumstances a good optimising compiler will be able to eliminate the temporary and construct what would be 'result' directly into 'myClass', leaving a single construction/destruction.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628401
• Total Posts
2982456

• 9
• 10
• 9
• 19
• 24