C++ std::make_shared

C++ std::make_shared

以下代码片段来自《C++ Concurrency In Action Practical Multithreading》一书第 152 页,一个线程安全堆栈 class。我的问题是为什么下面的 pop 函数(线程安全堆栈 class)不能只是 return std::make_shared<T>(std::move(data.top()),因为数据是 std::stack<T> 类型,因为 make_shared<T> returns一个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;
}

这是因为您需要将值存储在临时变量 (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
}