访问nullptr的可能性如何? [英] How is possible that accessing nullptr works?
问题描述
我有一个简单的课:
class B
{
public:
int getData() { return 3; }
};
然后,我使用nullptr初始化指向它的指针:
then, I initialize a pointer to it with nullptr:
B *foo{ nullptr };
然后,尝试使用它会带来惊喜:
And then, trying to use it comes the surprise:
int t = foo->getData();
,t现在是3.如果不构造类,这怎么可能?是因为getData()不使用"this"吗?那打破了我所有关于指针的知识.
and t is now 3. How is that possible without constructing the class? Is it because getData() does not use "this"? That broke all my knowledge about pointers.
这是预期的行为吗?我正在Visual Studio 2013中工作.
Is that expected behavior? I am working in Visual Studio 2013.
推荐答案
这是预期的行为吗?
Is that expected behavior?
不,它是 UB ,一切皆有可能.
No, it's UB, anything is possible.
是因为getData()不使用"this"吗?
Is it because getData() does not use "this"?
是的,可能会起作用,因为在特殊情况下不会使用this
,但不能保证任何事情.
Yes, it might work because this
won't be used in the special case, but nothing is guaranteed.
这篇关于访问nullptr的可能性如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!