问题
I have a simple class:
class B
{
public:
int getData() { return 3; }
};
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();
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.
Is that expected behavior? I am working in Visual Studio 2013.
回答1:
Is that expected behavior?
No, it's UB, anything is possible.
Is it because getData() does not use "this"?
Yes, it might work because this
won't be used in the special case, but nothing is guaranteed.
回答2:
It is undefined behavior, so you really should be very scared.
It might happen to apparently do something (on your implementation of C++), because the getData
function is not virtual and don't use any member of B
. So the generated code does not dereference the null pointer.
回答3:
It is undefined behaviour, you are accessing a member method from a nullptr
. No particular behaviour or outcome would be defined.
In this case though; given (cppreference):
The keyword
this
is a prvalue expression whose value is the address of the object, on which the member function is being called.
Since the NULL
value of this
is not being dereference - the member method is not virtual and doesn't access any member data of this
- it "seems" to work.
来源:https://stackoverflow.com/questions/35717934/how-is-possible-that-accessing-nullptr-works