2

We have a function GetString() that returns a std::string. We then have a function ConsumeString(char*) that consumes a C-style string.

Is it a bug to write ConsumeString(GetString().c_str())? To me it looks like this would be a bug because after c_str() runs, the original anonymous string will get destructed and you'll have a pointer to something that doesn't exist anymore. But weirdly, it always seems to work fine.

I only noticed it could be an issue when I tried to assign GetString().c_str() to a variable and then use it in two separate ConsumeString() functions, at which point it printed a corrupted string and the problem became obvious. But I don't know why it seems to work in the former case.

Is it potentially a bug that just happens to work, or does C++ specifically allow this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
stingray-11
  • 448
  • 2
  • 7
  • 25
  • 1
    The linked question does not answer this question; here it is about the lifetime of a temporary object, there it is about the lifetime of the C string. The linked question answers that the lifetime of the C string is linked to the lifetime of the string; here we want to know how long that string lives. – Daniel Jour Aug 05 '20 at 17:21

1 Answers1

3

Unless ConsumeString does some asynchronous processing of const char* provided to it (directly or indirectly) this code is very safe.

A temporary returned by GetString() will be alive until the function ConsumeString returns, so if it is done all it's business with it's argument before returning, everything will work correctly.

In your other scenario - I assume, you had something like this:

 const char* s = GetString().c_str(); // 1
 ConsumeString(s); // 2

temporary returned by GetString was destroyed after line 1 ended, so ConsumeString consumed an invalid pointer.

For a bit more formal wording regarding lifetime of temporary object, one might consult cppreference, in particular

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

SergeyA
  • 61,605
  • 5
  • 78
  • 137