任何人都可以解释将指向对象的指针设为 NULL 是什么意思吗?
当我们将一个对象的ptr赋值为NULL时,我们怎么还能访问成员函数呢?
class A
{
public:
void print()
{
cout<<"Hello";
}
}
int main()
{
A * a;
A* b = NULL;
a->print();
b->print();
}
编辑: 程序会崩溃吗? http://ideone.com/DudZ6
最佳答案
指针用于访问该对象的成员。如果您的函数不需要访问任何成员并且不是虚拟的,则它们实际上不使用该对象。该代码严格来说仍然是无效的,但不会崩溃。
如果您用打印“this”指针替换内容,它仍然可以工作,因为您没有取消引用它。
struct X {
void print() {
cout << "this pointer is " << this << endl;
}
};
int main() {
X *x;
x->print(); // will print whatever was on the stack, ie, random garbage
X *t = NULL;
t->print(); // will print a null pointer
}
如果您添加一个成员变量并打印它,或者将函数设为虚函数(因此必须通过对象本身查找它),它会崩溃。
struct X {
virtual void print() {
cout << "Hello World" << endl;
}
};
struct X2 {
int y;
void print() {
cout << "y is " << y << endl;
}
};
int main() {
X *x = NULL;
x->print(); // will crash on null pointer dereference
X2 *x2 = NULL;
x2->print(); // will crash on null pointer dereference
}
关于c++ - 理解指向设置为 NULL 的对象的指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855701/