1
votes

According to cplusplus.com, this is the implementation of the std::runtime_error class:

class runtime_error : public exception {
public:
  explicit runtime_error (const string& what_arg);
};

Since the constructor is explicit, I expected it to only accept std::string objects.

throw std::runtime_error("error message");

This code compiles (GCC), though. Shouldn't the compiler complain about the implicit const char* to const string conversion?

1
That's not how explicit works. It prevents a std::string from being converted to a std::runtime_error implicitly, not a const char * to a std::string. That one's up to std::string's constructor. - chris

1 Answers

5
votes

That is not what explicit means here. Maybe it is easiest to illustrate it with an example:

struct Foo
{
  explicit Foo(const std::string& s) {}
};

void bar(const Foo&) {}

int main()
{
  Foo f("hello");                // OK: explicit construction from std::string
  Foo f2 = std::string("hello"); // ERROR
  std::string s;
  bar(s);                        // ERROR
}

Here, the explicit converting constructor means you cannot implicitly construct a Foo from an std::string. But you can still construct an std::string from a const char*.