验证C ++中的指针 [英] Validating a pointer to a pointer in C++

查看:75
本文介绍了验证C ++中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个函数,该函数接收一个指针,使用它,然后使其指向新对象.为了做到这一点,我正在使用ptr-to-ptr.这就是我验证函数收到的ptr-to-ptr的方式:

I am trying to write a function that receives a pointer, uses it, and then makes it point to a new object. In order to do this, I am using a ptr-to-ptr. This is how I validate the ptr-to-ptr received by my function:

void modifyPtr(Obj ** ptrToPtr)
{
    if (*ptrToPtr == nullptr)
    {
        return;
    }
    else
    {
        // Do everything else!
    }
}

在撰写本文时,我想:如果客户端将以下内容传递给我的函数怎么办?

While writing this, I thought: what if a client passes the following to my function?

Obj ** ptrToPtr = nullptr;
modifyPtr(ptrToPtr);

在这种情况下,我的验证将很危险,因为我将取消引用nullptr.因此,我应该添加一个额外的验证步骤吗?

In that case, my validation will be dangerous, because I will be dereferencing a nullptr. So, should I add an additional step of validation?

void modifyPtr(Obj ** ptrToPtr)
{
    if (ptrToPtr == nullptr)
    {
        return;
    }
    else if (*ptrToPtr == nullptr)
    {
        return;
    }
    else
    {
        // Do everything else!
    }
}

我以前从未见过像这样的验证,这就是为什么我很犹豫.

I have never seen validation like this one before, which is why I am hesitant.

请注意,我知道应该避免在C ++中使用原始指针.我正在使用旧代码,发现这个问题很有趣.

Please be aware that I know one should avoid using raw pointers in C++. I am working with old code, and I find this problem interesting.

推荐答案

您的第一次验证是错误的,因为在检查ptrToPtr是否为空之前,您已对其取消引用.

Your first validation is wrong, because you dereference ptrToPtr before checking if it is null.

您可能不需要检查已取消引用的指针是否为null,因为无论如何都将对其进行更改(除非您需要对旧对象进行某些操作).

You probably don't need to check the dereferenced pointer for null since you are going to change it anyway (unless you need to do something with the old object).

但是,您应该更喜欢使用引用而不是双指针,例如:

However, you should prefer using references instead of double-pointers, eg:

void modifyPtr(Obj* &Ptr)

然后,调用者无法传递空引用(不进行难看的修改).

Then the caller can't pass in a null reference (without doing ugly hacks).

这篇关于验证C ++中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆