我是智能指针的新手。最近我开始进行一些并行模拟,我认为 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/