简体   繁体   English

C ++将指针的指针设置为null吗?

[英]C++ set a pointer of pointer to null?

I'm working on some kind of smart pointer technique but there is one piece I'm missing. 我正在研究某种智能指针技术,但我缺少一件。 I tried several combinations but the logic is as follow: 我尝试了几种组合,但逻辑如下:

UInt *obj = new UInt;
UInt *ref;
ref = obj;

delete obj;
obj = NULL;

if (ref == NULL)
{
    // It works
}
else
{
    // It failed
}

Is there any way to hit "It Works" without setting ref to NULL explicitly? 有什么方法可以在不将ref显式设置为NULL的情况下命中“ It Works”?

EDIT: 编辑:

A more appropriate scenario would be something like this: 一个更合适的方案是这样的:

class A
{
public:

    A(): ref(NULL) {}
    ~A()
    {
        if (ref != NULL)
            delete ref;
    }
    int *ref;
};

    int *obj = new int;
    A *host = new A();

    host->ref = obj; ???

    delete obj;
      obj = NULL;

    if (host->ref == NULL)
    {
        // It works.
    }
    else
    {
        // It failed.
    }

... ...

Can't use int*& ref as a class member though.... must be close. 但是不能将int *&ref用作类成员。

As you say, you should be using a smart pointer: 如您所说,您应该使用智能指针:

#include <memory>

std::shared_ptr<UInt> obj = std::make_shared<UInt>();
std::weak_ptr<UInt> ref = obj;

obj.reset();

if (ref.expired())
{
    // It works
}
else
{
    // It failed
}

Don't try managing your own memory when the standard library has facilities to do it for you. 当标准库具有为您做的设施时,请勿尝试管理您自己的内存。

Declare ref as a reference to pointer 声明ref作为对指针的引用

Uint*& ref = obj;

ref will now refer to the obj pointer. ref现在将引用obj指针。

Intially both obj and ref point to the (same) UInt instance. objref最初都指向(相同的) UInt实例。 Then you delete the instance and set obj to NULL . 然后删除实例并将obj设置为NULL But ref is just like any other regular pointer, so it still points to the deleted instance. 但是ref与其他任何常规指针一样,因此仍指向已删除的实例。

Instead you can create a reference variable, or in this case a 'reference pointer' by adding & to the declaration: 相反,您可以通过在声明中添加&来创建引用变量或本例中的“引用指针”:

Uint*& ref = obj;

Then ref really refers to obj and keeps the same value (pointer) as obj . 然后ref真指obj并保持相同的值(指针)作为obj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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