Question:
When is the destructor for a temporary object called when it is created within a function call but not used as a parameter? Specifically, consider the following code:
class StringBuffer { public: StringBuffer(std::string & str) : m_str(str) { m_buffer.push_back(0); } ~StringBuffer() { m_str = &m_buffer[0]; } char * Size(int maxlength) { m_buffer.resize(maxlength + 1, 0); return &m_buffer[0]; } private: std::string & m_str; std::vector<char> m_buffer; }; std::string mystring; GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
Answer:
The destructor for the temporary StringBuffer object is called after the call to GetString returns.
According to the C Standard (12.2 Temporary objects), the lifetime of a temporary object ends at the end of the full-expression that (a) does not itself appear as an operand (except in the construction of a class object) within another full-expression, and (b) is not part of a parenthesized expression.
In the example code, the call to GetString is the full-expression, and the temporary StringBuffer object is created within that expression. Therefore, the lifetime of the temporary object ends after the call to GetString returns.
This lifetime guarantee ensures that the temporary object remains valid until it is no longer needed. It allows expression templates to hold references to temporary objects because the temporaries will last until the expression is fully evaluated.
The above is the detailed content of When is a Temporary C Object's Destructor Called in a Function Call?. For more information, please follow other related articles on the PHP Chinese website!