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

5

Let's suppose I have a function:

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

As much as it seems normal, it gets kind of confusing when we think:

When the destructor of object x is called?

Please note:

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
}
    
asked by anonymous 11.08.2018 / 04:15

1 answer

9

Under normal conditions the destructor is called between return seen in code. The compiler inserts something there. What you may not know is that return is a code that does some things:

  • one of them is to result something, that is, it can execute an expression, in your case just get the value of a variable, and "send" to whoever called, most likely in a slot reserved in an expression in the calling, or even more common, function assigned to a variable, which is not a reserved slot.
  • Another is the return of the code execution control to the calling location, which we actually call return.

Do not see your code with something flat that a line is a thing being executed.

Having said all this, there is no need to call a destructor in this case and therefore 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 must remain alive because it will be used in the calling function. There is move and not delete , so it copies the pointer to the object, and keeps the object alive, and the caller may or may not destroy the object. At some point you must destroy it when there is no reference to it.

I do not know if it is from Portugal and it is used differently, in Brazil we use the term destructor.

    
11.08.2018 / 04:27