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?
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:
Which for your case means that once the assignment to
buffer
is done, the temporary object is destructed.