简体   繁体   中英

C++ Implicit conversion from bool to string

I have the following code, which compiles in Visual C++ 2012.

#include <string>

void func(std::string str)
{
}

void my_func()
{
    func(false);
}

The boolean 'false' is implicity passed into the string constructor

string(const char* _Ptr)

And then the pointer is null (because false = 0). Why does this compile, and should it compile according to the C++11 standard?

MSVC is mistakenly treating false as a null pointer constant. However, according to N4140, §4.10 [conv.ptr]/1 (emphasis mine):

A null pointer constant is an integer literal with value zero or a prvalue of type std::nullptr_t . A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.

The wording changed a bit from C++11, and you can find that discussion here . The verdict there was that it was an error in C++11 as well.

For visibility, TartanLlama provided the definition of "integer literal" below, according to [lex.icon]/1:

An integer literal is a sequence of digits that has no period or exponent part, with optional separating single quotes that are ignored when determining its value.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM