【问题标题】:unique_ptr double deletion eror messageunique_ptr 双重删除错误信息
【发布时间】:2019-11-04 00:42:44
【问题描述】:

编译这段代码后 我收到指示存在的错误消息 发生双重删除;我的问题是到底是什么 这段代码错了吗?问题出在哪里?

#include <iostream>
#include <memory>

class Manager;

class Interface {
protected:
  friend class InputListener;
  bool flag_;
};

class InputListener {
public:
  InputListener(std::shared_ptr<Interface> manager_ptr) {
    manager_ptr_ = std::move(manager_ptr);
    std::async(std::launch::async, &InputListener::Run, this);
  }

  void Run() {
    char c;
    std::cin >> c;
    manager_ptr_->flag_ = true;
  }

private:
  std::shared_ptr<Interface> manager_ptr_;
};

class Manager : public Interface {
public:
  Manager()
      : listener_ptr_{
            std::make_unique<InputListener>(std::shared_ptr<Manager>(this))} {}

  void Run() {
    while (true) {
      if (Interface::flag_)
        break;
    }
  }

private:
  std::unique_ptr<InputListener> listener_ptr_;
};

int main() {
  Manager m;
  m.Run();
  return 0;
}

为什么这段代码会产生这个错误? munmap_chunk(): 无效指针 中止(核心转储)

【问题讨论】:

    标签: c++ unique-ptr


    【解决方案1】:

    在这里,您在构造函数期间将 shared_ptr 传递给 'this'....

      Manager()
          : listener_ptr_{
                std::make_unique<InputListener>(std::shared_ptr<Manager>(this))} {}
    

    然而“this”是在堆上声明的:

      Manager m;
    

    这会在调用 InputListener 的 dtor 时出现问题。如果这是该类的预期用途,也许考虑将 manager_ptr_ 更改为 weak_ptr?

    【讨论】:

      【解决方案2】:

      您将 shared_ptr 包裹在一个已经具有销毁路径的 Manager 周围,因为它是在堆栈上实例化的。

      【讨论】:

      • 感谢您的快速反馈!我已将另一个答案标记为正确,因为它更详细。
      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2022-01-07
      • 1970-01-01
      • 2014-04-19
      • 2012-08-19
      相关资源
      最近更新 更多