假设以下代码:
Foo & foo = getFoo();
foo.attr; // 100% safe access?
Run Code Online (Sandbox Code Playgroud)
如果foo是一个指针,我会检查它是否NULL,但因为它是一个引用,这样的检查是不必要的.我想知道的是,是否有可能弄乱对象的引用,以致它将使访问其属性不安全.
我尝试了一些例子,比如试图转换NULL为Foo对象,但是我遇到了编译错误.我只是想确保上面的代码总是安全的,并且C++我不应该知道内在的黑魔法.
根据Benjamin的回答,我可以制作一个示例代码,我从引用中得到分段错误,因此它回答了我的问题.我会粘贴我的代码,万一有人对未来感兴趣:
#include <iostream>
using namespace std;
class B
{
public:
int x;
B() {x = 5;}
};
class A
{
public:
void f()
{
b = *(B*)NULL;
}
B & getB()
{
return b;
}
B b;
};
int main()
{
A a;
a.f();
cout << a.getB().x << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) c++ ×1