我有一个包含vector<shared_ptr<T>>的类:

using SharedItems = std::vector<std::shared_ptr<Item>>;

class LargeLift
{
public:
    SharedItems& getItems()
    {
        return _items;
    }

    void setSharedItems(SharedItems& items)
    {
        _items = items;
    }

private:
    SharedItems _items;
};

然后,我执行以下操作:
LargeLift b;
{
    LargeLift a;
    // Gets populated

    SharedItems& items = a.getItems();
    b.setSharedItems(items);
}

// Variable a is now out of scope

SharedItems& items2 = b.getItems();

如果a超出范围,最后一行是否有效?

最佳答案

如所写,您的代码是安全的-没有超出范围的内容。

在此示例中,a确实超出了范围,但是事情仍然很安全:

LargeLift b;
{
    LargeLift a;
    // Gets populated

    SharedItems& items = a.getItems();

    //give b its own copy
    b.setSharedItems(items);
}

// safe, because b owns its own copy
SharedItems& items2 = b.getItems();

在此示例中,它们是不安全的:
SharedItems* p_items;

LargeLift b;
{
    LargeLift a;
    // Gets populated

    items = &a.getItems();
}

// unsafe, items is already dangling
b.setSharedItems(*p_items);

SharedItems& items2 = b.getItems();

10-01 03:05