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...
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
std::string - the C++ String Class. C++ provides a simple, safe alternative to using char*s to handle strings. The C++ string class, part of the std namespace, allows you to manipulate strings safely.
There is no functionality difference between string and std::string because they're the same type.
std::any Class in C++ any is one of the newest features of C++17 that provides a type-safe container to store single value of any type. In layman's terms, it is a container which allows one to store any value in it without worrying about the type safety.
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.
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