检查构造函数的空值

  • 本文关键字:空值 构造函数 c++
  • 更新时间 :
  • 英文 :


我遇到了这个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";
   }
}

最新更新