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

标签 c++ c++11 pointers inheritance smart-pointers

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

关于c++ - 使用唯一的指针调用函数会使我的程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59314910/

相关文章:

c++ - 如何简化 x && (!y || (y && z))

c++ - 多类中的多线程

c++ - 使用 clang 对 std::atomic 函数的调用不明确

我可以同时将内存分配给不同的结构指针吗?

c++ - 静态库的内容

c++ - 自包含链表

c++ - std::make_shared 中的原始指针

c++ - 位域元素的默认值

c++ - 为什么多态性在没有指针/引用的情况下不起作用?

c# - 在 C# 中设置对 null 的引用