Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here’s an example 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; };
And here’s how you would use it:
// this is from a crusty old API that can't be changed void GetString(char * str, int maxlength); std::string mystring; GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
When will the destructor for the temporary StringBuffer object get called? Is it:
- Before the call to GetString?
- After GetString returns?
- Compiler dependent?
I know that C++ guarantees that a local temporary variable will be valid as long as there’s a reference to it – does this apply to parent objects when there’s a reference to a member variable?
Thanks.
The destructor for that sort of temporaries is called at the end of the full-expression. That’s the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice.
It’s in fact what makes expression templates work: They can keep hold references to that sort of temporaries in an expression like
Because every temporary will last until the expression
Is evaluated completely. It’s quite concisely described in
12.2 Temporary objectsin the Standard.