Guaranteed Lifetime of Temporary in C
When a temporary variable is created within a function call but not utilized as a parameter, the C language provides a guarantee for its lifetime. Let's explore this concept in relation to a hypothetical class called StringBuffer.
In the StringBuffer class example, a temporary StringBuffer object is created within the Size() method call and passed to the GetString() function. The question arises about when the destructor for this temporary object will be invoked.
According to the C standard, the destructor for such temporary objects is called at the end of the full-expression. This refers to the most outer expression that is not part of any other expression, which in this case occurs after GetString() returns and the value is evaluated. Therefore, the temporary StringBuffer object will remain valid throughout the execution of GetString().
This behavior is crucial for techniques such as expression templates, as it allows variables to hold references to temporary objects within complex expressions like e = a b * c / d, ensuring that these temporaries remain valid until the entire expression is evaluated.
The above is the detailed content of How Long Does a C Temporary Object Live Within a Function Call?. For more information, please follow other related articles on the PHP Chinese website!