Reputation: 52519
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?
Upvotes: 3
Views: 182
Reputation: 409166
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.
Upvotes: 6
Reputation: 2369
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.
Upvotes: 4