执行类方法时崩溃但智能指针删除了对象

禅诺2

我遇到了 C++ 内存管理和智能指针的问题。我有一个代码来向你展示这个问题:

#include <memory>

class Closeable
{
 public:
  virtual void Close() = 0;
};

class DisconnectionHandler
{
 public:
  virtual void HandleDisconnection() = 0;
};

class EventHandler
{
 public:
  virtual void HandleEvent() = 0;
};

class Notifier
{
 public:
  virtual void OnDisconnection() = 0;
};

class RemoteSystem : public Closeable
{
 public:
  void SetReceiveDataEventHandler(const std::shared_ptr<EventHandler>& receive_data_event_handler) {
    this->receive_data_event_handler_ = receive_data_event_handler;
  }

  void Close() override { this->receive_data_event_handler_ = nullptr; }

  // In this example to simplify the code I just call this method from the main function.
  void OnDataReceived() { this->receive_data_event_handler_->HandleEvent(); }

 private:
  std::shared_ptr<EventHandler> receive_data_event_handler_;
};

class ReceiveDataEventHandler : public EventHandler
{
 public:
  explicit ReceiveDataEventHandler(const std::shared_ptr<DisconnectionHandler>& disconnection_handler)
      : disconnection_handler_(disconnection_handler) {}

  void HandleEvent() override {
    // Some code of receiving data.
    // But we can find out that connection was closed and we must call the disconnection handler.
    if (this->IsConnectionClosed()) {
      this->disconnection_handler_->HandleDisconnection();
      return;
    }
    // Some other stuff..
  }

 private:
  [[nodiscard]] bool IsConnectionClosed() const {
    // In the example code I just return true.
    return true;
  }

 private:
  const std::shared_ptr<DisconnectionHandler> disconnection_handler_;
};

class RemoteSystemDisconnectionHandler : public DisconnectionHandler
{
 public:
  explicit RemoteSystemDisconnectionHandler(const std::shared_ptr<Closeable>& closeable_remote_system,
                                            Notifier* notifier)
      : closeable_remote_system_(closeable_remote_system), notifier_(notifier) {}

  ~RemoteSystemDisconnectionHandler() { printf("Destructed.\n"); }

  void HandleDisconnection() override {
    this->closeable_remote_system_->Close();
    printf("Closed.\n");
    this->notifier_->OnDisconnection();
    printf("Notified.\n");
  }

 private:
  const std::shared_ptr<Closeable> closeable_remote_system_;
  Notifier* const notifier_;
};

class ClientNotifier : public Notifier
{
 public:
  void OnDisconnection() override { printf("Disconnected.\n"); }
};

int main() {
  ClientNotifier notifier;

  auto remote_system = std::make_shared<RemoteSystem>();

  {
    // Scope for losing references in the main function after SetReceiveDataEventHandler.
    auto disconnection_handler = std::make_shared<RemoteSystemDisconnectionHandler>(remote_system, &notifier);
    auto receive_data_event_handler = std::make_shared<ReceiveDataEventHandler>(disconnection_handler);
    remote_system->SetReceiveDataEventHandler(receive_data_event_handler);
  }

  // Only in the example.
  remote_system->OnDataReceived();

  return 0;
}

您也可以运行此代码。在这个例子中程序崩溃就行了this->notifier_->OnDisconnection()程序的输出:

Destructed.
Closed.
*crash*

发生这种情况是因为ReceiveDataEventHandler调用方法时丢失了对 的最后一个引用,因此,丢失了对 的引用并删除了此对象。方法和删除类的两个对象之后它返回到方法并打印“Closed”。到输出,但由于对象已经被删除,下一行出现错误,因为现在RemoteSystem::CloseRemoteSystemDisconnectionHandler::HandleDisconnectionRemoteSystemDisconnectionHandlerCloseRemoteSystemDisconnectionHandlerReceiveDataEventHandlerRemoteSystemDisconnectionHandler::HandleDisconnectionthis被删除并且对它的任何访问都会发生内存异常。我还尝试在 Java 上重写此代码,它运行良好,与 C++ 不同。所以想请教各位C++社区有没有解决这个问题的方法?我认为 C++ 在内存管理方面没有问题,因为智能指针存在,但显然我错了。希望得到您的帮助!提前致谢!

艾伦·伯特尔斯

一个简单的解决方案是shared_ptr在调用方法之前制作一个副本

    void OnDataReceived()
    { 
        auto temp = this->receive_data_event_handler_;
        if (temp)
        {
            temp->HandleEvent();
        }
    }

temp 将保持指针活动直到方法调用完成。

但是请注意,如果您在实际代码中使用多个线程,std::shared_ptr则不是线程安全的,因此您需要引入互斥锁来保护对receive_data_event_handler_以下内容的访问

class RemoteSystem : public Closeable
{
public:
    void SetReceiveDataEventHandler(const std::shared_ptr<EventHandler>& receive_data_event_handler) {
        this->receive_data_event_handler_ = receive_data_event_handler;
    }

    void Close() override 
    { 
        std::unique_lock lock(mutex);
        this->receive_data_event_handler_ = nullptr;
    }

    // In this example to simplify the code I just call this method from the main function.
    void OnDataReceived()
    { 
        std::shared_ptr<EventHandler> temp;
        {
            std::unique_lock lock(mutex);
            temp = this->receive_data_event_handler_;
        }
        if (temp)
        {
            temp->HandleEvent();
        }
    }

private:
    std::shared_ptr<EventHandler> receive_data_event_handler_;
    std::mutex mutex;
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章