检查空引用?

jma*_*erx 7 c++

让我们说你有这样的事情:

int& refint;
int* foo =0;
refint = *foo;
Run Code Online (Sandbox Code Playgroud)

你怎么能验证引用是否是NULL为了避免崩溃?

Ste*_*end 11

你不能迟到初始化这样的引用.它必须在声明时进行初始化.

在Visual C++上,我得到了

错误C2530:'refint':必须初始化引用

用你的代码.

如果您"修复"代码,则在VC++ v10中的引用时间内会发生崩溃(严格来说,未定义的行为).

int* foo = 0;
int& refint(*foo);
int i(refint);  // access violation here
Run Code Online (Sandbox Code Playgroud)

保证安全的方法是在参考初始化或分配时检查指针.

int* foo =0;
if (foo)
{
  int& refint(*foo);
  int i(refint);
}
Run Code Online (Sandbox Code Playgroud)

虽然这仍然不能保证foo指向可用内存,但是当引用在范围内时它也保持不变.


CB *_*ley 5

当你有一个"null"引用时,你没有未定义的行为.在尝试通过取消引用指针来形成引用之前,应始终检查指针是否为null.

(您的代码是非法的;您无法创建未初始化的引用并尝试通过分配它来绑定它;您只能在初始化期间绑定它.)