Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何为指针解引用自动添加保护?_C++_Pointers - Fatal编程技术网

C++ 如何为指针解引用自动添加保护?

C++ 如何为指针解引用自动添加保护?,c++,pointers,C++,Pointers,取消引用无效指针或智能指针时,代码崩溃。添加断言以帮助查找问题。比如说, Type* p = NULL; // Always initilize to be null. assert(p); // Add before dereferencing to help to find the problem. p->f(); // Crashes if p is invalid. #define PTR_RUN(p, f) assert(p); p->f; 我的问题是如何在取消引用指针

取消引用无效指针或智能指针时,代码崩溃。添加断言以帮助查找问题。比如说,

Type* p = NULL; // Always initilize to be null.
assert(p); // Add before dereferencing to help to find the problem.
p->f(); // Crashes if p is invalid.
#define PTR_RUN(p, f) assert(p); p->f;
我的问题是如何在取消引用指针时自动添加断言。比如说,

Type* p = NULL; // Always initilize to be null.
assert(p); // Add before dereferencing to help to find the problem.
p->f(); // Crashes if p is invalid.
#define PTR_RUN(p, f) assert(p); p->f;
这是可行的,但可读性不好,并且可能由于不小心使用宏而存在一些隐藏的问题。还有更好的办法吗?谢谢。

通常人们会写信

if ( p ) p->f

 p && p->f
使用短路和运算符

通常人们会写

if ( p ) p->f

 p && p->f

使用短路和运算符

或者在某些情况下值得使用引发异常的某种智能指针

或者在某些情况下值得使用引发异常的某种智能指针

您可以为给定类型重载运算符
->
,并可能在其中添加断言函数。我从未这样做过,但它可能会工作。

您可以为给定类型重载运算符
->
,并可能在其中添加断言函数。我从来没有这样做过,但可能会奏效。

它们是不同的。如果是您的情况,p可以是有效的,也可以是无效的。这两种情况都必须在包含函数中处理。在我的例子中,p被断言总是有效的。断言用于查找代码错误。@user1899020一个不能简单地检测无效的非空指针。它们是不同的。如果是您的情况,p可以是有效的,也可以是无效的。这两种情况都必须在包含函数中处理。在我的例子中,p被断言总是有效的。断言用于查找代码错误。@user1899020不能简单地检测无效的非空指针。已尝试但无效。要运行函数
操作符->()
,指针必须有效。因此,在检查
操作符->()
中的指针有效性之前,它会崩溃。尝试过但没有工作。要运行函数
操作符->()
,指针必须有效。因此,它在检查
操作符->()
中的指针有效性之前崩溃。