Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stack with unique_ptr

Tags:

c++

unique-ptr

I have a legacy program that uses a std::stack object to store some pointers.

std::stack<Widget*> widgetStack;

Now I want to change this to the new C++11 style

std::stack<std::unique_ptr<Widget>> widgetStack;

However in the code there is a function:

Widget* getLastWidget()
{
    if(!widgetStack.isEmpty())
    {
        return widgetStack.top();
    }
    return null;
}

I'm struggeling to get this function to work with the unique_ptr. The stack is the owner of the widgets and only when the stack is popped, should the Widget objects be destroyed. Any ideas on how I can fix this?

like image 658
Frank Avatar asked Sep 18 '25 11:09

Frank


2 Answers

If the stack is the only owner of the pointer, then it is recommended to return the raw pointer, because raw pointer means "a pointer without ownership":

Widget* getLastWidget()
{
    if(!widgetStack.isEmpty())
    {
        return widgetStack.top().get();
    }
    return nullptr;
}
like image 118
llllllllll Avatar answered Sep 20 '25 03:09

llllllllll


I personally don't like using raw pointers. You can simply change std::unique_ptr to std::shared_ptr, as suggested by @user202729

std::stack<std::shared_ptr<Widget>> widgetStack;

std::shared_ptr<Widget> getLastWidget()
{
    if(!widgetStack.isEmpty())
    {
        return widgetStack.top();
    }
    return nullptr;
}

This way the pointers are still managed by the stack and you don't have to deal with them in raw form.

I suggested references in the comments, but it wouldn't be too good solution. Returning reference makes it difficult to return indication of empty stack (like the nullptr in your example).

like image 37
Yksisarvinen Avatar answered Sep 20 '25 03:09

Yksisarvinen