Lifetime of temporary objects

202 Views Asked by At

I encountered the following code (roughly):

struct StringBuffer {
    StringBuffer(const char* string) {strcpy(m_buffer, string);}
    const char* c_str() const {return m_buffer;}
    char m_buffer[128];
};


std::string foobar() {
    const char* buffer = StringBuffer("Hello World").c_str();
    return std::string(buffer);
}

Am I correct in assuming that after the line:

    const char* buffer = StringBuffer("Hello World").c_str();

buffer is pointing to a pointer in a deconstructed StringBuffer object?

2

There are 2 best solutions below

3
On BEST ANSWER

To answer your question at the end, yes, buffer will be a stray pointer.

To answer the more general question about lifetime of temporary values, I suggest you read this reference which says:

... all temporaries are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created...

Which for your case means that once the assignment to buffer is done, the temporary object is destructed.

0
On

Yes.

By convention, functions like std::string::c_str() aren't meant for caching because even if it pointed to a non-temporary object, it could be invalidated by a re-allocation of the string it points to.