0

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;
}
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Alan Zeng
  • 74
  • 1
  • 7
  • 2
    Ignoring the fat that `top` doesn't remove an item from a `stack`, the code is basically just error-checking around your suggestion. – Stephen Newell Mar 25 '18 at 04:20
  • @StephenNewell, I am pretty new to C++, I am used to the syntax of "res = ....." in other programming languages, for saving result to a local variable. Forgot the code here is just calling a copy constructor for share_ptr. Thanks! It makes sense to me now. – Alan Zeng Mar 25 '18 at 04:35
  • Please show the code of your proposed version. Where does it call data.pop()? – n. m. could be an AI Mar 25 '18 at 05:32

1 Answers1

0

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
}
tenta4
  • 304
  • 2
  • 16