Is the destructor of the class called on the assignment?

Is the destructor of a class called when a variable that already contains an object gets another object in C ++ code?

Car car1;
Car car2;

car1 = car2;

      

Is the destructor called car1

in this situation?

+3


source to share


5 answers


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).

+1


source


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.

+4


source


Car car1();//error, Car car1; call default construct function
Car car2(); //error, Car car2;call default construct function

car1 = car2; //call operator=() 

      

+1


source


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;
}

      

0


source


car1 = car2;

      

this results in the destructor car1

NOT being executed.
if you want the destructor to be called, car1

you need to name it Explicitly or it should go out of scope (as our Friend Baum myrten said, the call is car1

Explicitly rarely needed).

0


source







All Articles