Is it possible to initialize a std::string
without creating a variable?
What I wish to accomplish:
throw std::runtime_error("Error: " + strerror(errno));
What I do currently:
std::string error = "Error: ";
std::string errmsg(strerror(errno));
throw std::runtime_error(error + errmsg);
std::basic_string is a class template for making strings out of character types, std::string is a typedef for a specialization of that class template for char .
How to Create a Vector of Strings in C++ The program begins with the inclusion of the iostream library, which is needed for keyboard input, and output to the terminal (screen). This is followed by the inclusion of the string library, which is needed for automatic composing of strings.
We'd like to initialise it. For example: class UserName { std::string mName; public: UserName(const std::string& str) : mName(str) { } }; As you can see a constructor is taking const std::string& str .
Just make a temporary out of one of them:
throw std::runtime_error(std::string("Error: ") + strerror(errno));
The operator+
overload for std::string
can take const char*
as well as std::string
.
If you have access to C++14, you can using namespace std::literals
and do it this way:
throw std::runtime_error("Error: "s + strerror(errno));
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