简体   繁体   中英

Why is my destructor called twice?

Suppose I hace a class Student with the method:

Student Student::method(Student x)
{
    //nothing important
    return x;
}

The copy constructor is called twice, once when the object x is send as a parameter and second when x is returned from the function.

Why and when is the destructor for class Student called twice when I call this method? The call is like this: a = b.method(c), where a, b and c are Student objects.

For your example, a = b.method(c); , there are three copies that may take place, save for copy elision. The first is when the c object is copied into the function parameter x . The second is when the x object is returned from the function. The third is when the return value is copied into the a object. The first two involve the copy constructor and the last involves the copy assignment operator, unless you change it to Student a = b.method(c); , in which case they all use the copy constructor.

a , b , and c will all be destroyed at the end of their scope. The object x will be destroyed at the end of the method function. The return value of the function will be destroyed at the end of the full expression that contains it - that is, once a = b.method(c); has finished.

However, not all of these copies must occur - the compiler is allowed to elide or omit the copy/move construction of a class under certain situations. The first copy into the function parameter will occur. The second copy out of the function will be treated as a move first, before attempting to copy it. This copy or move may be elided. The final copy, from temporary return value to a , will occur if you're using copy assignment, but may be elided if you use the copy constructor (as in Student a = b.method(c); ).

If two Student objects are constructed, they must be destructed. The copies into the parameter and out of the return value need destructing.

The destructor for x is called when the function returns (after x has been copied in to the return value).

The destructor for the return value is called at the end of the full-expression containing the function call (unless the return value has its lifetime extended by being assigned to a reference).

Every object with automatic storage duration that is constructed will automatically be destructed (usually in reverse order of construction). You construct two objects ( x and the return value) and so there are two destructor calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM