5
std::string getMyString() { return <make a string>; }

...

HANDLE something = OpenSomething(getMyString().c_str(), ...);

I've read Guaranteed lifetime of temporary in C++ and I believe that the temporary string will live until the assignment has been evaluated, i.e. plenty long enough to make this work as expected.

Having once before run into an std::string lifetime-related bug (can't remember what it was) I'd rather double-check...

Community
  • 1
  • 1
Roman Starkov
  • 59,298
  • 38
  • 251
  • 324

3 Answers3

8

The destructor for the temporary will not be called until after the function call returns, so what we see here is safe.

However if the called function saves the char* and it ends up being used somehow after OpenSomething has returned, then that's one fine dangling pointer.

Jon
  • 428,835
  • 81
  • 738
  • 806
7

Yes, this is fine. :-)

The string will be destroyed at the end of the statement, at the semi colon.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

If you don't use any other argument of OpenSomthing for returning pointer to getMyString.c_str() everything will be OK.

MaksBrrr
  • 1
  • 2