1

I made a really simple program to try fusing unique pointers and inheritance together. But, it ends up crashing with exit code 11 and I don't know why. Can Anyone explain the reason for the crash?

//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);
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Josee
  • 141
  • 1
  • 2
  • 12

1 Answers1

5

The pointer p is default-initialized and points to nothing.

Constructs a std::unique_ptr that owns nothing. Value-initializes the stored pointer and the stored deleter.

Dereference on it leads to UB, anything is possible.

The behavior is undefined if get() == nullptr

You should make p pointing to a valid object, e.g.

std::unique_ptr<Stuff> p = std::make_unique<Stuff>();
songyuanyao
  • 169,198
  • 16
  • 310
  • 405