jmueck
jmueck

Reputation: 13

string automatically converts const char* to std::string

I stumbled upon this by receiving an "no instance for constructor" error when using std::out_of_range constructor code with older compilers

For some older compilers the definition of std::out_of_range is

class out_of_range : public logic_error {
public:
      out_of_range(const string& message);
};

in more recent versions they've added a second constructor

class out_of_range : public logic_error {
public:
      out_of_range(const string& message);
      out_of_range(const char *message);
};

The code I was trying to compile did the following constructor call:

std::out_of_range("Some Error Message");

after adding #include <string>

The compiler was able to convert const char* to std::string ?

Is that the expected behavior?

Upvotes: 1

Views: 113

Answers (1)

MSalters
MSalters

Reputation: 179789

Yes, that's expected, because the relevant constructor std::string::string(const char*) is not explicit, which means it's available for implicit conversions like this.

Upvotes: 5

Related Questions