0

给定这样的功能:

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;
}

作为基类 BLECommand 是这样的:

class Command {

protected:
    std::shared_ptr<Receiver> pReceiver_;

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

由于双重删除 BLEReceiver 对象(ble),我有一个错误,我不知道因为发生了这种情况。shared_ptr 类应该避免这种情况。

为了调试这个问题,我在 BLEReceiver 类的析构函数中放了一个打印,这是设备控制台上的输出:

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...

有什么想法可以解决这个问题吗?提前致谢。

编辑:

基类的声明是这样的:

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;
   };

定义是这样的:

void InfoCMD::Execute() const{

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

  this->pReceiver_->SendData();

}
4

1 回答 1

0

好的,您的代码没有突出显示错误,实际上我尝试使用以下代码重现该错误:

// Example program

#include <iostream>
#include <memory>
#include <unistd.h>

using namespace std;

class BLEReceiver {
    public:
        BLEReceiver(){i =1;}
        virtual ~BLEReceiver(){std::cout << "destroyed" << std::endl;}
    private:
    int i;
};


class BLECommand {

protected:
    std::shared_ptr<BLEReceiver> pBLEReceiver_;

public:
    BLECommand(std::shared_ptr<BLEReceiver> receiver) : pBLEReceiver_(receiver) {}
    virtual ~BLECommand() {}
    virtual void Execute() const {std::cout << "execute"<<std::endl;};
};

int main()
{
    std::shared_ptr<BLEReceiver> ble(std::make_shared<BLEReceiver>());

    BLECommand *idreq = new BLECommand(ble);

    idreq->Execute();
    delete idreq;
    sleep(1);
    BLECommand *versionreq = new BLECommand(ble);
    versionreq->Execute();
    sleep(1);
    delete versionreq;
}

它与输出完美配合:

execute
execute
destoyed

你可以在C++ Shell上试​​试。

所以你的代码中的问题是其他代码。可能你用错了shared_ptr,让这个指针使用的内存在delete调用之前就被销毁了。

于 2020-10-22T08:36:01.683 回答