I'm working on RVO/Copy-Constructor/Destructor and checking code by randomly. I'm little confused here why destructor called three time..??
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "Simple Constructor" << endl;
}
A(const A& obj){
cout << "Copy Constructor " << endl;
}
A operator =(A obj){
cout << "Assignment Operator" << endl;
}
~A(){
cout << "Destructor " << endl;
}
};
A fun(A &obj){
cout << "Fun" << endl;
return obj;
}
int main(){
A obj;
obj=fun(obj);
cout << "End" << endl;
return 0;
}
Output:
Simple Constructor // ok
Fun // ok
Copy Constructor // ok for =
Assignment Operator // ok
Destructor // ok for =
Destructor // why here destructor called?
End // ok
Destructor // ok for main
I was expecting Destructor to be called two times.
One for (=) operator's Object.
Second one for int main()'s object.
Why is it being called the third time? And how?
A operator =(A obj){
cout << "Assignment Operator" << endl;
}
You declared the function A::operator= as having a return type (an instance of A in this case), but the implementation has no return statement. This is undefined behavior.
You are essentially asking about the response to undefined behavior. The answer is "anything goes". In your case, with your compiler and your system, you are getting one more call to the destructor than to the constructors. You're lucky that you didn't your program didn't create nasal demons or erase your hard drive.
The solution is simple: Don't invoke undefined behavior. The canonical way to write a copy assignment operator is to have the return type be a reference to the class and to return *this:
A& operator =(A obj){
cout << "Assignment Operator" << endl;
return *this;
}
With this correction, you'll see that calls to the various constructors and calls to the destructor balance.
Suppose you instead used a non-standard copy assignment operator (but with a properly written return statement):
A operator =(A obj){
cout << "Assignment Operator" << endl;
return *this;
}
Once again you would see that calls to the constructors and to the destructor balance. How many calls you will see depends on your compiler and on the optimization level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With