Search code examples
c++c++11make-shared

C++ std::make_shared


The following code snippet is from the book C++ Concurrency In Action Practical Multithreading page 152, a thread-safe stack class. My question is why the following pop function (of the thread-safe stack class) can't just return std::make_shared<T>(std::move(data.top()) instead, where data is of type std::stack<T> since make_shared<T> returns a shared_ptr? Thank you in advance!

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;
}

Solution

  • This because you need to store value in temporary variable (res), before it will destructed by pop() call.

    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
    }