Recently I found the bug in the following code:
ostringstream o;
o << "some string";
const char* s = o.str().c_str(); // empty string instead of expected "some string"
This is explained by cppreference.com: the copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer.
I don't have any problem fixing this bug, however, I have many places in the projects, which look like this:
ostringstream o;
o << "error description";
throw my_exception(o.str().c_str());
...
my_exception::my_exception(const char* s) :
message(s) // message is std::string
{}
Does this code has undefined behavior, like the first code fragment?
No, message(s) is a std::string so you take a copy of the contents of the char buffer at that point.
The temporary lasts for the scope of the function you call it with - in this case the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With