返回右值参考

问题描述 投票:3回答:2

我正试图了解我正在查看的代码:

class ShipFactory
{
public:
    Ship make_ship(....) { ... }

    static std::unique_ptr<ShipFactory>&& get_factory()
    {
        if (!m_factory) {
            m_factory.reset(new ShipFactory);
        }
        return std::move(m_factory);
    }

    ...
public:
    static std::unique_ptr<ShipFactory> m_factory;
};

std::unique_ptr<ShipFactory> ShipFactory::m_factory;

...

// used like this:
ship = ShipFactory::get_factory()->make_ship(...);

我的问题是关于get_factory方法。我真的不明白为什么它会返回一个对std :: unique_ptr的rvalue引用或者它会做什么。我也不完全相信它是有效的。

c++
2个回答
1
投票

auto_ptr不同,你不能复制一个unique_ptr,因为那个构造函数被删除了,这对于unique_ptr没有任何意义,因为它拥有它所指向的内存,但你可以移动它。这就是这里发生的事情,重置一个unique_ptr,然后移动它。它具有与以下相同的效果:

auto ship = make_unique<ShipFactory>();

0
投票

请记住,std::move不会移动任何东西;它只允许移动发生(并导致rvalue引用(可能)在重载决策中移动为首选)。

返回一个右值引用(离开函数时未被销毁的东西!)是对象的资源提供给客户端:

auto s=ShipFactory::get_factory()->make_ship(…);  // use the current factory
auto f=ShipFactory::get_factory();  // take the whole current factory

如果没有当前工厂,两条线都会创建工厂;第二个原因导致此后没有现在的工厂(但仍然可以使用unique_ptr f)。

© www.soinside.com 2019 - 2024. All rights reserved.