Destructor Destructor - 6 months ago 43
C++ Question

Why implicit conversion of bool to string isn't an error?

I goggled it & tried to find similar question on SO also but didn't find anything useful. So, posting my question here.

Consider this program:

#include <iostream>
void foo(const std::string &) {}
int main()

[Warning] converting 'false' to pointer type for argument 1 of 'std::basic_string::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]' [-Wconversion-null]

Why C++ allows this without explicit cast? I was expecting to get compiler error. The program abnormally terminates at runtime due to exception displaying following:

terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

What the standard says about this type of implicit conversion?


Before C++11 introduced the nullptr keyword, null pointers were a bit of a hack. Any integer literal equal to zero would suffice as a null pointer constant, and false fit the bill.

So, the effect of your program is to construct the std::string with a char const * argument of NULL. The constructor doesn't support null pointers, so you get undefined behavior.

The solution to this problem is to use a newer dialect of C++. Pass -std=c++11 to the compiler if necessary, or -std=c++14. Then you should get something like this:

error: no matching function for call to 'foo'

EDIT: Hmm, GCC doesn't appear to implement this change yet. That's a bit surprising. You might try Clang.

I've filed a bug report.