我正在声明一个指针,我没有初始化它,但是当我调用该方法时它工作正常,在那种情况下它不应该为访问未初始化的对象而给出段错误?
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "CONSTRUCTORr\n";
}
void myMethod() {
std::cout << "METHOD\n";
}
};
int main() {
MyClass* myClass = nullptr;
myClass->myMethod();
return 0;
}
上面代码的输出是0,打印出文本“METHOD”
最佳答案
I am declaring a pointer, I do not initialize it
MyClass* myClass = nullptr;
实际上,您确实初始化了指针。它指向 null。
when I call the method it works normal, in that case it should not give segment fault for accessing an uninitialized object?
没有。不能保证通过 null 调用成员函数会“产生段错误”(请注意,也不能保证它不会“产生段错误”)。
程序的行为是未定义的。
The output of the code above is 0, and prints the text "METHOD"
这是一种潜在行为。所有其他行为也是可能的,因为没有定义任何行为。
关于c++ - 访问未初始化的对象。这怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62939761/