Home >Backend Development >C++ >When Are C Temporary Objects Destroyed?
Guaranteed Lifetime of Temporary Objects in C
In C , a temporary variable is created when an expression evaluates to a value that is not stored in a named variable. In the given code, a temporary StringBuffer object is created within the GetString() function call:
StringBuffer(mystring).Size(MAXLEN)
The question arises as to when the destructor for this temporary object will be called:
Lifetime of Temporary Objects:
C guarantees that a temporary object's lifetime extends until the end of the full-expression in which it is created. A full-expression is the outermost expression that is not part of any other expression. In this case, the full-expression is the entire GetString() function call:
GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
Destruction Timing:
Therefore, the destructor for the temporary StringBuffer object will be called after the GetString() function returns and the value is evaluated. This behavior is guaranteed by the C Standard in 12.2 "Temporary objects."
Significance for Expression Templates:
This lifetime guarantee is crucial for expression templates, which can hold references to temporary objects within expressions. For instance, the following expression template:
e = a + b * c / d
Can retain references to the temporary objects created by each operand because each temporary object's lifetime extends until the end of the entire expression.
The above is the detailed content of When Are C Temporary Objects Destroyed?. For more information, please follow other related articles on the PHP Chinese website!