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

前端 未结 3 1636
失恋的感觉
失恋的感觉 2021-01-12 22:24

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:

#         


        
3条回答
  •  囚心锁ツ
    2021-01-12 22:40

    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'
    

    http://coliru.stacked-crooked.com/a/7f3048229a1d0e5a

    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.

提交回复
热议问题