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?