Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a proper use of a temporary std::string?

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...

like image 608
Roman Starkov Avatar asked Mar 27 '11 13:03

Roman Starkov


People also ask

Why do we use std::string?

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.

Is std::string safe?

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.

Is std::string the same as string?

There is no functionality difference between string and std::string because they're the same type.

What is std :: Any used for?

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.


1 Answers

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.

like image 131
Jon Avatar answered Sep 28 '22 16:09

Jon