Validating a pointer to a pointer in C++

独自空忆成欢 提交于 2019-12-11 16:59:06

问题


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);

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.

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.


回答1:


Your first validation is wrong, because you dereference ptrToPtr before checking if it is 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).




回答2:


If you just return the new pointer instead of modifying the parameter, you can get away with just one level of indirection and simpler validation. The caller can decide if they want to reassign it immediately to the old value.




回答3:


//use reference.

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

Obj * ptrToPtr = nullptr;
modifyPtr(ptrToPtr);



回答4:


In your first if you do not dereference anything. You just check if the passed pointer is null or not. So you do not have to worry. Just remove the * which i have not noticed on my mobile



来源:https://stackoverflow.com/questions/48178943/validating-a-pointer-to-a-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!