stringstream.str() lifetime

Can someone confirm that the std::string created by the stringstream.str() call is only destroyed AFTER the writeMessage function has ended?

I don't need to keep a separate, named std::string, right?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Example program
#include <string>
#include <sstream>
#include <cstring>

char full_message[255];

void writeMessage(const char* message)
{
    strcpy(full_message, message);
}

int main()
{
    std::stringstream err;
    err << "Error message";
    writeMessage(err.str().c_str());
}

Thanks.
You are correct.

The compiler, in essence, creates a local context for all the arguments to a function. The context is only destroyed after the function returns.
In general, temporary objects created in an expression live until the end of the full-expression. A full-expression is any expression that isn't a sub-expression.

Typically, this means that temporaries live until the entire line of code is finished.
Last edited on
Thanks ;)
Topic archived. No new replies allowed.