Lifetime of temporary objects

I came across 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

points to a pointer in a deconstructed object StringBuffer

?

+3


source to share


2 answers


To answer your question at the end, yes buffer

will be a wandering pointer.

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



... all temporary files are destroyed as the last step in evaluating a complete expression that (lexically) contains the point at which they were created ...

Which for your case means that after completing the task, the buffer

temporary object will be destroyed.

+7


source


Yes.



By convention, functions like std :: string :: c_str () are not meant to be cached because even if it pointed to a non-temporary object, it could be invalidated by reallocating the string it points to.

+4


source







All Articles