When is the destroyer of an object called in C++?

Asked

Viewed 129 times

4

Let’s assume I have a function:

std::string empty_string() {
    std::string x{ "" };
    return x;
}

As normal as it sounds, it gets a little fuzzy when we think:

When the destroyer of the object x is called?

Observe:

std::string empty_string() {
    std::string x{ "" };
    //se o destruidor for chamado aqui, x vai ser deletado antes de ser retornado 
    return x;
    //qualquer coisa depois do return é inutil
}

1 answer

8


Under normal conditions the destructor is called between the return seen in the code and the last statement that computed something (including one that is in the return). The compiler inserts something there. What you may not know is that the return is a code that does some things:

  • one of them is result in something, that is, it can execute an expression, in your case it is only take the value of a variable, and "send" to whom called, most likely in a slot reserved in an expression in the calling function, or even more commonly assigned to a variable, which is nevertheless a slot reserved.
  • another is the back from code execution control to caller location, what we actually call return.

Between one and the other the compiler would place the call from the destructor of string.

Don’t see your code as something flat that a line is a thing being executed.

Having said all that, there is no need to call destructor in this case and so nothing will be inserted in this code. There is the insertion of a value copy code, because it is not to destroy anything, the object needs to stay alive because it will be used in the calling function. There’s a move and not a delete, So it copies the pointer to the object, and it keeps the object alive, and the caller can, or cannot, destroy the object. At some point it is necessary to destroy, when there is no reference to it.

I do not know if it is from Portugal and there is used different, in Brazil we use the term destrutor.

  • Maniero, the behavior of both object destructors and object pointers is the same?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.