Lifespan of anonymous instances

R

richardclay09

In this snippet:

void f(const char* c) {...use c in a read-only way...}

std::eek:stringstream oss;
oss << "blah blah";
f(oss.str().c_str());

oss.str() returns a *copy* of the buffer as a std::string. In this case
this copy is anonymous, and the return value of its c_str() method is
passed to f(). Is the anonymous std::string instance guaranteed (by the
standards) to last long enough for f() to safely use its c_str() value?
 
G

Greg

In this snippet:

void f(const char* c) {...use c in a read-only way...}

std::eek:stringstream oss;
oss << "blah blah";
f(oss.str().c_str());

oss.str() returns a *copy* of the buffer as a std::string. In this case
this copy is anonymous, and the return value of its c_str() method is
passed to f(). Is the anonymous std::string instance guaranteed (by the
standards) to last long enough for f() to safely use its c_str() value?

Yes.

Only after the call to f() completes will the object passed as a
parameter be destroyed.

Greg
 
R

richardclay09

Thanks, but what was worrying me in this case is that it is not the
anonymous instance *itself* that is being passed as a parameter, but
the return value of one of its methods - does your answer still apply
in that case?

Ta
Richard
 
R

richardclay09

Thanks, but what was worrying me in this case is that it is not the
anonymous instance *itself* that is being passed as a parameter, but
the return value of one of its methods - does your answer still apply
in that case?

Ta
Richard
 
G

Gabriel

Thanks, but what was worrying me in this case is that it is not the
anonymous instance *itself* that is being passed as a parameter, but
the return value of one of its methods - does your answer still apply
in that case?

Yes.

The result of c_str() is valid until you call the next non-const
memberfunction of the string. The temporary string in your example is
valid until f returns (at which point the string is destroyed and thus
the result of c_str() also becomes invalid)

Gabriel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top