Home > Mobile >  When does c right value destruct in this scenario?
When does c right value destruct in this scenario?

Time:11-16

Here is the code:

class SomeType {
public:
SomeType() {}
~SomeType() {}

std::string xxx;
}
bool funtion_ab() {
    SomeType(); // This is a right val; 
    // The right val destructs here when I test the code. I want to make sure that it would always destructs here.
    int a = 0, b = 10;
    ....// other code
    return true; 
} 

Please tell me if you know the truth. Thank you!

CodePudding user response:

What you have is called a temporary object. From §6.7.7,

Temporary objects are created

  • when a prvalue is converted to an xvalue

or, more specifically,

[Note 3: Temporary objects are materialized:

...

  • when a prvalue that has type other than cv void appears as a discarded-value expression ([expr.context]).

— end note]

and, on the lifetime, the same section has this to say

Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.

You can read more about the expression semantics, but in your case "full-expression" is fairly unambiguous.

SomeType();

The "full-expression" containing your constructor call is... the constructor call itself. So the destructor will be called immediately after evaluating the constructor. There are some exceptions to this rule (such as if the temporary object is thrown as an exception or is bound as a reference), but none of those apply here.

As noted in the comments, compilers are free to inline your constructor and destructor calls and then are free to notice that they do nothing and omit them entirely. Optimizers can do fun stuff with your code, provided it doesn't change the semantics. But a strict reading of the standard states that the destructor is called exactly where you suggested.

  •  Tags:  
  • c 11
  • Related