Home >Backend Development >C++ >How Long Do Temporary Objects Live in C Expressions?

How Long Do Temporary Objects Live in C Expressions?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-26 05:36:31854browse

How Long Do Temporary Objects Live in C   Expressions?

Lifetime of Temporary Objects in C

In C , temporary objects are created when expressions are evaluated. The reference to a temporary object is valid until the end of its full-expression, which is the outermost expression where the temporary object is not part of another expression. This allows temporary objects to be used as arguments in function calls and returned from functions.

Consider the following example:

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;
};

void GetString(char * str, int maxlength);

std::string mystring;
GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);

In this example, a temporary StringBuffer object is created and its Size() method is called to obtain a pointer to a buffer. This pointer is then passed to the GetString() function.

The lifetime of the temporary StringBuffer object is guaranteed until the end of the full-expression, which is the call to GetString(). Therefore, the destructor for the temporary object will be called after GetString() returns. This behavior is consistent regardless of the compiler being used.

This guaranteed lifetime is crucial for expression templates, which rely on the fact that temporary objects will remain valid until the end of the expression in which they are created.

The above is the detailed content of How Long Do Temporary Objects Live in C Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn