Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create inline std::string

Tags:

c++

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);
like image 454
drum Avatar asked Jul 24 '17 00:07

drum


People also ask

What is std:: basic_ string?

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 do you create a vector of strings?

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.

How to initialize string in class?

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 .


1 Answers

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));
like image 97
Nicol Bolas Avatar answered Sep 21 '22 16:09

Nicol Bolas