0

Is this code safe? Just because it runs with no errors, I'm concerned I'm setting a trap for myself.

void targetMethod( const char *arg );
std::string helperMethod( char *text ) { return std::string( text ); }

targetMethod( helperMethod().c_str() ); 

helperMethod() returns a std::string, and the calling code gets its underlying char*, and passes it to targetMethod(). I'm concerned that the returned string is temporary, so taking its underlying char* is dangerous. So instead I should do something like this:

std::string myTemp = helperMethod( "hello" );
targetMethod( myTemp.c_str() );
MJF
  • 83
  • 9

2 Answers2

2

The temporary will live until the end of the expression (until the semicolon) so it is safe.

Having said that, I'm not sure why you need helperMethod at all since you can construct a std::string from a const char *.

Anon Mail
  • 4,660
  • 1
  • 18
  • 21
  • "so it is safe" -- as long as `targetMethod` doesn't save a copy the pointer. – lcs May 08 '17 at 15:39
  • Yes. The other answers added the "copy the pointer" caveat and are correct. – Anon Mail May 08 '17 at 15:39
  • helperMethod() does more in the real world; it looks like it does in the example only to show what's happening. – MJF May 09 '17 at 11:02
2

It depends upon what targetMethod does. If it stores the pointer away for later use, then no, it's not safe. But if it just uses it for the duration of the function call, then yes, it is safe. The lifetime of the string extends to the end of the full expression in which it is created.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274