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
?
source to share
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.
source to share