如何防止传递NULL指针? [英] How to prevent the passing of a NULL-pointer ?

查看:97
本文介绍了如何防止传递NULL指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.

有没有办法
获取编译器错误消息
通过将NULL(显式)传递给指针参数,请? :)

Hello.

Is there a way
to get a compiler error message
by passing of NULL (explicitly) to a pointer parameter, please ? :)

void f(CWnd* pcTest)
{
}

void test()
{
  // would like to get an "error" here
  f(NULL);
}


f(const CWnd&)f(CWnd*&)
的情况 已被检查.

谢谢 ! :)


The cases of f(const CWnd&) and f(CWnd*&)
are already checked.

Thank you ! :)

推荐答案

最好的方法是更改​​函数原型,使其接受对CWnd对象的引用:
The best way is to change the function prototype such that it accepts a reference to a CWnd object:
void f(CWnd &obj)
{
 //blah
}

void test()
{
 //f(NULL); //compiler error!
 CWnd wnd;
 f(wnd); //will succeed.
}


如果您正在编写多线程程序,则可能需要考虑线程安全性.


If you''re writing a multithreaded program, you might want to take thread safety into account.


我认为这是不可能的,因为NULL是有效的指针,到目前为止就编译器而言.这仅表示指针当前未指向任何对象,这可能是程序员想要的.您可以将NULL重新定义为某些非法值,但这可能会在其他地方破坏您的代码.
I don''t think that is possible, since NULL is a valid pointer, as far as the compiler is concerned. It just means that the pointer currently does not point to any object, which may be what the programmer wants. You could redefine NULL to some illegal value, but that would probably break your code elsewhere.


一个技巧是提供单独的重载:

One trick is to provide a separate overload:

void f(char c);



这使得字面0的呼叫不明确.重载不需要实现.如果需要,您必须指定f((CWnd *)0)来选择正确的重载.

但是,我不建议您使用它.它的价值值得怀疑,因为它甚至无法捕获:



which makes calls with a literal 0 ambiguous. The overload doesn''t need an implementation. You''d have to specify f((CWnd*)0) to pick the correct overload if needed.

However, I would not recommend to use that. It''s of questionable value, since it wouldn''t even catch:

CWnd * wnd = 0;
f(wnd);



(在编译时无法捕获-至少不容易捕获).

在f()中使用简单的ASSERT应该可以解决问题-或按照建议传递引用.



(which can''t be caught - at least not easily - at compile time).

A simple ASSERT within f() should do the trick - or pass a reference, as suggested.


这篇关于如何防止传递NULL指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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