简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM