C++/CLI 如何判断句柄是否指向任何对象

C++/CLI how do I tell if a handle isn't pointing to any object

在普通的 c++ 中,有些指针如果不指向任何对象,则用 NULL 表示。

class* object1 = NULL; //NULL is a special value that indicates
                       //that the pointer is not pointing to any object.

if(object1  == NULL) {
    cout << "the pointer is not pointing to any object" << endl;
}
else {
    cout << "the pointer is pointing to any object" << endl;
} 

那么使用 C++/CLI 句柄会是什么样子呢? 我在网上找到了这个。谁能告诉我我对此是否正确?

class^ object2 = nullptr;
if(object2 == nullptr){
    cout << "the pointer is not pointing to any object" << endl;
}
else {
    cout << "the pointer is pointing to any object" << endl;
}

你不应该在 C++ 中使用 NULL。选择 nullptr.

考虑一下:

void some_function(some_class* test);
void some_function(int test);

int main()
{
    some_function(NULL);
}

由于我们人类将 NULL 解释为指针 "type,",因此程序员可能希望调用第一个重载。但是 NULL 通常被定义为整数 0 —— 因此编译器会 select 第二个。如果您了解正在发生的事情,这不是一个问题,但它不是很直观。

另外,0 一个有效的内存地址。在桌面编程中,我们通常不会将数据分配到地址 0,但它可能在其他一些环境中有效。那么我们可以做什么来检查 0 的分配?

为了消除歧义,C++ 具有显式 nullptr。它不是一个整数,它有自己的特殊类型,不能被误解:这个指针有一个强类型的 empty 值。