jeudi 22 octobre 2020

Problem with atributte shared_ptr in class base and derived

Given something function like this:

void process() {
  std::shared_ptr<Receiver> receiver(std::make_shared<Receiver>());

  Command *cmd1 = new InfoCMD(receiver,10);
  cmd->Execute();
  delete cmd;
  DELAY_MS(1000);
  Command *cmd2 = new InfoCMD(ble,20);
  cmd2->Execute();
  DELAY_MS(1000);
  delete cmd2;
}

Being the base class BLECommand like this:

class Command {

protected:
    std::shared_ptr<Receiver> pReceiver_;

public:
    Command(std::shared_ptr<Receiver> receiver) : pReceiver_(receiver) {}
    virtual ~Command() {}
    virtual void Execute() const = 0;
};

I have a error due a double delete BLEReceiver objetct (ble) and I don't have idea because happens that. The shared_ptr class should avoid this.

For debug this issue, I have put a print in the destructor of BLEReceiver class, and this is the output on the device console:

W (9932) Receiver: delete receiver
W (10872) Receiver: delete receiver
CORRUPT HEAP: multi_heap.c:172 detected at 0x3ffbddcc

abort() was called at PC 0x4008d873 on core 0
Setting breakpoint at 0x40089a0a and returning...

Any idea to solve this problem? Thanks in advance.

Edit:

The declaration of base class is this:

class InfoCMD : public Command { 
   private:
   uint32_t info;
   public:
   InfoBLECMD(std::shared_ptr<BLEReceiver>  receiver,uint32_t info) :    
              Command(receiver),                                                                                         
              info(info){};                                                                                         
   ~InfoCMD(){}
   void Execute() const;
   };

And the definition is something like this:

void InfoCMD::Execute() const{

  this->pReceiver_->setData(this->info);

  this->pReceiver_->SendData();

}

Aucun commentaire:

Enregistrer un commentaire