引用可以为空吗?
我从维基百科上读到:
“引用不能为空,而指针可以;每个引用都引用某个对象,尽管它可能有效也可能无效。”
但是,我不相信这一点,因为以下代码编译时没有错误:
class person
{
public:
virtual void setage() = 0;
};
int main()
{
person *object = nullptr;
person &object1 = *object;
}
I have read from the Wikipedia that:
“References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.”
However, I don’t believe this because of following code, which compiles with no error:
class person
{
public:
virtual void setage() = 0;
};
int main()
{
person *object = nullptr;
person &object1 = *object;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在您的代码中:
您取消引用 NULL 指针,因此您会得到未定义的行为。为了回答你的问题,不存在 NULL 引用这样的东西。
为了解决问题的另一部分,仅仅因为程序可以编译,并不能保证它是正确的或它会工作。 C++ 编译器甚至不需要尝试诊断代码包含的错误类型。
In your code:
you dereference a NULL pointer, so you get undefined behaviour. And to answer your question, there is no such thing as a NULL reference.
And to address the other part of your question, just because a program compiles, there is no guarantee that it is correct or that it will work. C++ compilers are not required to even attempt to diagnose the kind of error your code contains.
person &object1=*object
与person &object1=NULL
不同。也许编译器不够聪明,无法发现您正在取消引用空指针,但无论如何您都会收到运行时错误。所以它们仍然是真实的;)Saying
person &object1=*object
is not the same thing as sayingperson &object1=NULL
. Probably the compiler is just not smart enough to find out that you are dereferencing null pointer, but you'll get a runtime error anyway. So they are kind of true still ;)您可以有一个空引用,不知道为什么有人会说,否则,这是某些操作的令人讨厌的副作用。您只是无法直接创建一个。
You can have a null reference, not sure why anyone would say otherwise, it is a nasty side effect of some operations. You just can't create one directly.
那会让你的程序崩溃。你尝试运行它吗?
执行 *object 将遵循空指针,因此实际上您的引用永远不会被分配。
that would crash your program. Did you try running it?
doing *object will deference a null pointer, so in fact your reference never gets assigned.
好吧,您可以在 C++ 中做您想做的任何事情。另一个例子:
除了您提到的情况之外,您在上述情况下还调用了未定义的行为!
Well, you can do whatever you want in C++. Another example:
You are invoking an undefined behavior in the above case, beside the case you mentioned!
clang 3.5 甚至对稍后可能对引用进行 NULL 检查发出警告:
clang 3.5 even warns on a possible later NULL check of a reference:
gcc8 会给出警告:
一个小演示:
编译并运行输出:
gcc8 will give a warning about it:
A small demo:
Compile and running output: