Topic: Question about object destruction time


Author: ab4ds@hotmail.com ("adeht")
Date: Mon, 15 Nov 2004 19:50:03 GMT
Raw View
Consider the following:

std::string foo();
void goo(const char *);

goo(foo().c_str());

Is it legal? My belief is that it is not, because:

1) std::string::c_str() returns a const char * that, in this case,
gets invalidated when the string is destroyed.
2) The string might get destroyed before the call to goo()
is evaluated.

Am I right?


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: ron@sensor.com (Ron Natalie)
Date: Mon, 15 Nov 2004 20:19:48 GMT
Raw View
adeht wrote:

> std::string foo();
> void goo(const char *);
>
> goo(foo().c_str());
>
> Is it legal? My belief is that it is not, because:
>
> 1) std::string::c_str() returns a const char * that, in this case,
> gets invalidated when the string is destroyed.
> 2) The string might get destroyed before the call to goo()
> is evaluated.
>
> Am I right?

You're right on #1, but you're wrong on #2, and your general premise
is a maybe.

The c_str() return value becomes invalid as soon as a non-const member
(including the destrutor) is called on the string object.   So yes, it
goes away when the value is destructed.

However, the temporary value that foo() returns will live until the end
of the full expression is created in.   This will be until after goo()
returns.

So, if goo doesn't store the pointer somewhere peristant things are OK.
It can be assured that the pointed to characters will remain valid until
it returns.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]