使用唯一指针调用函数会使我的程序崩溃

Using a unique pointer to call a function crashes my program

我做了一个非常简单的程序来尝试将唯一指针和继承融合在一起。但是,它最终以退出代码 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);
}

指针 pdefault-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>();