Scott
Scott

Reputation: 1186

C++ abuse of string concatenation

So I've generated some code over the last few months, maybe more, where I've use the C++ string library to concatenate strings. Like so:

template< typename T >
string tostr( const T & val ); // implmented wherever

void somelibraryfunction( const char * );

// begin actual code

somelibraryfunction( ( "foo" + tostr( 5 ) ).c_str( ) );

This compiles and works fine. My concern is the string temporary that is created is destroyed after an address to it's c_str is taken, and I'm just relying on reading the recently freed but uncleared memory. Any thoughts?

Upvotes: 2

Views: 269

Answers (1)

Rob Kennedy
Rob Kennedy

Reputation: 163247

The temporary string is not destroyed until the entire statement has completed, which isn't until after the library function returns. As long as the function doesn't save a copy of that address somewhere for later use, your code is fine. (Storing a copy of the string contents is fine; it just shouldn't store the char* pointer value, which becomes invalid when the temporary string goes away.)

Upvotes: 6

Related Questions