0

以下代码片段来自 C++ Concurrency In Action Practical Multithreading 第 152 页,一个线程安全的堆栈类。我的问题是为什么下面的 pop 函数(线程安全堆栈类的)不能只是return std::make_shared<T>(std::move(data.top()),其中 data 是类型,std::stack<T>因为make_shared<T>返回 a shared_ptr?先感谢您!

std::shared_ptr<T> pop()
{
std::lock_guard<std::mutex> lock(m);
if(data.empty()) throw empty_stack();
std::shared_ptr<T> const res(std::make_shared<T>(std::move(data.top())));
data.pop();
return res;
}
4

1 回答 1

0

这是因为您需要将值存储在临时变量 (res) 中,然后它才会被 pop() 调用破坏。

std::shared_ptr<T> pop()
{
    std::lock_guard<std::mutex> lock(m);
    if(data.empty()) throw empty_stack();
    // data.pop(); will remove top element
    return std::make_shared<T>(std::move(data.top())); // top element has not changed
}
于 2018-03-25T18:22:02.510 回答