是否使用NULL引用确定? [英] Is using NULL references OK?

查看:165
本文介绍了是否使用NULL引用确定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个代码:

void f(const std::string &s);

然后呼叫:

f( *((std::string*)NULL) );

我想知道别人怎么想这个结构,应该使用一些默认值(它计算)而不是一些用户提供的值。

And I was wondering what others think of this construction, it is used to signal that function f() should use some default value (which it computes) instead of some user provided value.

我不知道该怎么想,它看起来很奇怪,但你觉得

I am not sure what to think of it, it looks weird but what do you think of this construction?

推荐答案

否。这是未定义的行为,可以导致代码做任何事情(包括重新格式化你的硬盘,核心倾销或侮ing你的母亲)。

No. It is undefined behaviour and can lead to code to do anything (including reformatting you hard disk, core dumping or insulting your mother).

如果你需要能够通过NULL,然后使用指针。引用的代码可以假设它引用有效对象。

If you need to be able to pass NULL, then use pointers. Code that takes a reference can assume it refers to a valid object.


补充: C ++ 03标准(ISO / IEC 14882,2 nd 2003)在§8.3.2参考第4段中说:

Addendum: The C++03 Standard (ISO/IEC 14882, 2nd edition 2003) says, in §8.3.2 "References", paragraph 4:


引用应初始化为引用有效的对象
或函数。 [注意:特别是,一个空引用不能存在于一个定义良好的程序中,因为只有
方法来创建这样的引用将绑定到对象通过取消引用一个空指针
获得,这会导致未定义的行为。
如9.6中所述,引用不能直接绑定到位字段。 ]

A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]

[强调加入粗体]

这篇关于是否使用NULL引用确定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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