c++ - std::move() 与 priority_queue.top()

标签 c++ c++11 shared-ptr move

我是智能指针的新手。最近我开始进行一些并行模拟,我认为 shared_ptr 将有助于防止内存泄漏。我听说增加实例数会导致不可忽略的额外时间开销,所以我希望避免这样做。

在我的代码中,我使用 priority_queue 来管理模拟中的事件。为了确保我了解这些容器中的 shared_ptr 会发生什么,我做了一些测试:

std::priority_queue<std::shared_ptr<Base>> queue;
queue.push(std::make_shared<Derived>());
std::shared_ptr<Base> p = queue.top();
//std::shared_ptr<Base> p = std::move(queue.top());

std::cout << "Created a shared Derived (as a pointer to Base)\n"
          << "  p.get() = " << p.get()
          << ", p.use_count() = " << p.use_count() << '\n';

使用以上两种不同的方式从priority_queue中获取指针,我本以为第二种方式在use_count()中返回1。但是,无论我是否使用 std::move() 获取队列中的顶部指针,我都看到了 2 的值。我用 g++ -std=c++0x [FileName]

编译

谁能指出我哪里做错了?以上两种方法是否表明我还有额外的时间开销?

最佳答案

priority_queue::top返回一个 const& 到顶部元素。

std::shared_ptr<Base> p = queue.top();

上面的行创建了一个新的 shared_ptr,它现在与 priority_queue 中的 shared_ptr 共享顶部元素的所有权,所以 use_count 为 2。

std::move 不会影响结果,因为 moving a const object将调用 shared_ptr 复制构造函数,与上面的行相同。

要使 use_count 保持在 1,请使用

std::shared_ptr<Base> const& p = queue.top();

关于c++ - std::move() 与 priority_queue.top(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49165009/

相关文章:

C++ cwchar 错误

visual-studio-2010 - 从托管代码中包含时未定义 shared_ptr

c++ - 将此指针转换为 boost::shared_ptr?

c++11 - 如何在 C++ 中将shared_ptr<FILE> 转换为FILE*?

C++ 指向一个对象然后移动它的内存位置

Android:使用 NDK 构建 native GUI 应用程序?

c++ - 将 boost::asio tcp 示例移植到 C++11

c++ - 模板<类 T> 错误

c++ - std::function 作为模板参数

c++ - 为什么具有私有(private)构造函数的类不阻止从此类继承?如何控制哪些类可以从某个基类继承?