Help debugging basic_string<char>

Neil Bird neil@fnxweb.com
Mon Jan 23 14:06:00 GMT 2006


Around about 23/01/06 09:16, Jamie Kirkpatrick typed ...
>> std::string getString();
>> void f()
>> {
>>     const char* p = getString().c_str();
>>     // use p
>> }
>>
> Ok - this is what I meant.  So what im seeing is correct OK, thats good 
> I guess!  Is there something in the c++ spec i can point people too to 
> indicate that this is the case?  An out of interest - how come the 
> destructor on string is not getting called so soon?

   Nothing specific, it's more about understanding what's happening. 
getString is returning a transient std::string which will only live for the 
duration of the statement.  You're calling .c_str() on this, and that's fine. 
  But at the end of the statement (after the assignment) the string goes out 
of scope, its destructor is called and the memory opinted to by the c_str() is 
invalid.

   You have two alternatives;  if getString() is accessing a long term store 
you can guarantee will be around, you can make it return a reference, maybe 
even a const ref. (which would be better), so you're not accessing the 
transient but the original.

   Alternatively, keep a copy yourself:

const std::string& getString();
void f()
{
     const char* p = getString().c_str();
     // use p
}

or

std::string getString();
void f()
{
     const std::string s = getString;
     const char* p = s().c_str();
     // use p
}


>  Also, is it ok to 
> assume that the following is valid?
> 
> int test( char * buffer );
> main()
> {
>     int result = test( someFunctionReturningString().c_str() 
> );            // buffer valid for duration of subsequent call?
> }

   Yes;  in this case the transient string is valid till after 'test' returns. 
  The specs. probably got something to say about the lifetime of objects 
created on the stack for function calls.


   Can't help with the rest as I've not done that sort of thing.


-- 
[neil@fnx ~]# rm -f .signature
[neil@fnx ~]# ls -l .signature
ls: .signature: No such file or directory
[neil@fnx ~]# exit



More information about the Libstdc++ mailing list