Is the destructor of the class called on the assignment?
In the following program, you can see that the destructor is not called for t1 or t2 until the end of the main () function:
#include <iostream>
#include <string>
class Test
{
std::string _name;
public:
Test(std::string name) : _name(name) { }
~Test()
{
std::cout << "Destructor " << _name << std::endl;
}
Test& operator=(const Test& fellow)
{
// avoid changing the name of the object
std::cout << "Assignment operator "
<< _name << "=" << fellow._name << std::endl;
return *this;
}
};
int main()
{
Test t1("t1"), t2("t2");
t1 = t2;
return 0;
}
In the assignment, t1=t2
only the assignment operator is called on t1
, taking t2
as a parameter. If you need to free up resources t1
, you can do so in an assignment statement implemented as the sample code shows. Remember to also implement a copy constructor - for cases of assignment to an uninitialized instance (there is no need to release previously saved resources, because there are no resources at the time the copy constructor is called).
source to share
The destructor car1
will not be executed when you do
car1 = car2;
On car1
will only be called (possibly implicitly generated) Car::operator= (const Car&);
.
The destructor will only be called when it car1
goes out of scope (or when you call it explicitly, but you rarely need it).
Also note that it car1
does not "hold" the instance Car
, it is the instance itself.
source to share
Well it depends. If you allocate memory on the heap and assign one variable to another, it won't call the destructor:
{
Car* car1 = new Car();
Car* car2 = new Car();
car1 = car2;
}
But it will, and that is because it is out of scope not because of the purpose of the copy.
{
Car car1;
Car car2;
car1 = car2;
}