Released C ++ pointer was not highlighted with a concise example

#include<iostream>

class base{
  public:
  base(){};
  base ( base& b ) {};
  virtual void run(){};
  ~base(){std::cout<<"destructor for base"<<std::endl;};
};

class derived : public base {
   int alpha;
   public:
   derived ( ): alpha (0), base() {};
   derived ( base& b ) : alpha(0), base(b) {};
   void run(){};
   int* get_address () { return &(this->alpha); };
   ~derived(){std::cout<<"destructor for derived"<<std::endl;};
};

void make_derived ( std::shared_ptr<base>& b ){
    b.reset ( new derived () );
}

int main(){
  std::shared_ptr<base> b;
  make_derived ( b ) ;
  std::shared_ptr<derived> d = std::dynamic_pointer_cast<derived> (b);

  std::shared_ptr<int> a ( d->get_address() );

  b->run();
}

      

I compiled this code and ran it. The error message was "there was no pointer deallocation." This is a fairly common error message. I do not however understand why something liberated appears. He dies right after std::shared_ptr<int> a ( d->get_address() );

. Does anyone know how to fix this?

+3


source to share


1 answer


Not delete

that you didn't new

. When you pass a pointer to a constructor shared_ptr

or reset

, you set a pending call on delete

that pointer (assuming you are not doing a custom deaerator either). What's going on here:

std::shared_ptr<int> a ( d->get_address() );

      



You are passing the address of the constructor int

to the constructor shared_ptr

. But for was int

not allocated new

, so should not be processed shared_ptr

.

+1


source







All Articles