gpt4 book ai didi

c++ - 检查空引用?

转载 作者:可可西里 更新时间:2023-11-01 18:16:35 28 4
gpt4 key购买 nike

假设您有这样的事情:

int& refint;
int* foo =0;
refint = *foo;

如何验证引用是否为 NULL 以避免崩溃?

最佳答案

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

在 Visual C++ 上我得到

error C2530: 'refint' : references must be initialized

用你的代码。

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

int* foo = 0;
int& refint(*foo);
int i(refint); // access violation here

确保此安全的方法是在引用初始化或赋值时检查指针。

int* foo =0;
if (foo)
{
int& refint(*foo);
int i(refint);
}

尽管这仍然不能保证 foo 指向可用内存,也不能保证当引用在范围内时它仍然如此。

关于c++ - 检查空引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4270589/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com