为什么访问这个空指针不会引发异常?
Why doesn't accessing this nullpointer cause an exception?
#include <iostream>
class TestClass {
public:
TestClass() {
std::cout << "TestClass instantiated\n";
}
~TestClass() {
std::cout << "TestClass destructed\n";
}
void PrintSomething() {
std::cout << "TestClass is printing something\n";
}
};
int main() {
TestClass* tClass = new TestClass();
delete tClass;
tClass = nullptr;
tClass->PrintSomething();
std::cout << "Exiting...\n";
return 0;
}
结果:
TestClass instantiated
TestClass destructed
TestClass is printing something
Exiting...
我认为在 tClass 指针设置为 nullptr 后尝试打印某些内容会导致空指针异常错误,但它打印得很好。
Why doesn't accessing this nullpointer cause an exception?
因为没有指定引发异常。通过空指针访问会导致未定义的行为。别这样。
#include <iostream>
class TestClass {
public:
TestClass() {
std::cout << "TestClass instantiated\n";
}
~TestClass() {
std::cout << "TestClass destructed\n";
}
void PrintSomething() {
std::cout << "TestClass is printing something\n";
}
};
int main() {
TestClass* tClass = new TestClass();
delete tClass;
tClass = nullptr;
tClass->PrintSomething();
std::cout << "Exiting...\n";
return 0;
}
结果:
TestClass instantiated
TestClass destructed
TestClass is printing something
Exiting...
我认为在 tClass 指针设置为 nullptr 后尝试打印某些内容会导致空指针异常错误,但它打印得很好。
Why doesn't accessing this nullpointer cause an exception?
因为没有指定引发异常。通过空指针访问会导致未定义的行为。别这样。