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?
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*
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.