我遇到了这个C++代码:
if (Foo f = "something")
{
...
}
if
条款到底在检查什么? 构造函数的计算结果是否可以为 NULL?
编辑:
Foo是一个类
if子句检查到底是什么?构造函数的计算结果是否可以为 NULL?
该行等效于:
// Create a new scope
{
// Create the object in the new scope
Foo f = "something";
// Use if
if ( f )
{
...
}
}
如果有一个用户定义的函数将Foo
转换为bool
,这将起作用。否则,它将不起作用。与 NULL 没有直接关系。但是,如果用户定义的转换为任何类型的指针,则
if ( f ) { ... }
与
if ( f != NULL ) { ... }
如果您使用 C++11,那也与
if ( f != nullptr ) { ... }
示例 1(这不起作用(:
struct Foo
{
Foo(char const*) {}
};
int main()
{
Foo f = "something";
// Does not work.
// There is nothing to convert a Foo to a bool
if ( f )
{
std::cout << "truen";
}
}
示例 2(这确实有效(:
struct Foo
{
Foo(char const*) {}
// A direct conversion function to bool
operator bool () { return true; }
};
int main()
{
Foo f = "something";
if ( f )
{
std::cout << "truen";
}
}
示例 3(这确实有效(:
struct Foo
{
Foo(char const*) {}
// A direct conversion function to void*
operator void* () { return this; }
};
int main()
{
Foo f = "something";
if ( f )
{
std::cout << "truen";
}
// Same as above
if ( f != NULL )
{
std::cout << "truen";
}
// Same as above
if ( f != nullptr )
{
std::cout << "truen";
}
}