Zhen
Zhen

Reputation: 4283

How to do a Stack of unique_ptr

Imagine you have a stack of unique_ptr to something (an int to simplify), like:

std::stack< std::unique_ptr<int> > numbers;
numbers.push( std::unique_ptr<int>( new int(42)) );

But if you try to use the top element, without getting it from the stack, you will get an compile error:

if( not numbers.empty() ){
    auto lastone = numbers.top();
    std::cout << "last " << *lastone << std::endl;
}

You should move out the element, use it, and then put again in the stack:

if( not numbers.empty() ){
    auto lastone = std::move(numbers.top());
    numbers.pop();
    std::cout << "last " << *lastone << std::endl;
    numbers.push( std::move(lastone) );
}

Is there a better way to do this?

Upvotes: 1

Views: 401

Answers (1)

syam
syam

Reputation: 15069

If you don't intend to actually pop the element but just want to use it inplace, just use a reference:

auto& lastone = numbers.top();
std::cout << "last " << *lastone << std::endl;

Upvotes: 4

Related Questions