我编写了一个非常简单的程序,尝试将唯一的指针和继承融合在一起。但是,它最终因退出代码11而崩溃,我不知道为什么。任何人都可以解释崩溃的原因吗?
//Counter Class, Base class
class Counter {
public:
virtual int addStuff(int& x)=0;
};
//Derived Class, child class of Counter
class Stuff:public Counter {
public:
virtual int addStuff(int& x) override;
};
//Main function using unique pointers to call addStuff from Stuff class
int main() {
int x = 12;
std::unique_ptr<Stuff> p;
p->addStuff(x);
}
最佳答案
指针p
是default-initialized,指向什么都没有。
Constructs a
std::unique_ptr
that owns nothing. Value-initializes the stored pointer and the stored deleter.
Dereference会导致UB,一切皆有可能。
The behavior is undefined if
get() == nullptr
您应该使
p
指向有效对象,例如std::unique_ptr<Stuff> p = std::make_unique<Stuff>();
关于c++ - 使用唯一的指针调用函数会使我的程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59314910/