Frank
Frank

Reputation: 2696

C++ stack with 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?

Upvotes: 4

Views: 2347

Answers (2)

Yksisarvinen
Yksisarvinen

Reputation: 22201

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).

Upvotes: 2

llllllllll
llllllllll

Reputation: 16404

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

Upvotes: 8

Related Questions