Lifetime of Temporary Objects in C
C ensures that a temporary variable's lifetime extends to the end of the full expression it's constructed within. This applies to temporary objects like those created in function calls without being passed as parameters.
For instance, consider the following class:
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; };
If we use this class as follows:
// Crusty old API that cannot be changed void GetString(char* str, int maxlength); std::string mystring; GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
The destructor for the temporary StringBuffer object will be called after GetString returns. This behavior is guaranteed by the C standard and allows for reliable use of temporary objects in function calls.
The standard specifies that the lifetime of a temporary object extends to the end of the full-expression, which is the outermost expression that is not part of any other expression. In this case, the full-expression is the function call, so the temporary object's lifetime extends until the function returns.
This guarantee is crucial for expression templates, which can hold references to temporary objects within complex expressions. It ensures that the objects remain valid until the entire expression is evaluated.
The above is the detailed content of How Long Do C Temporary Objects Live?. For more information, please follow other related articles on the PHP Chinese website!