在函数调用中访问并移动unique_ptr

cqd*_*234 3 c++ unique-ptr

我有一个类似于以下的部分.

struct derive : base{
    derive(unique_ptr ptr): base{func(ptr->some_data), std::move(ptr)}{}
};
Run Code Online (Sandbox Code Playgroud)

从理论上讲,它应该有效.但由于编译器(vs2015)并未严格遵循标准,因此func(ptr->some_data), std::move(ptr)未定义顺序,ptr即可在访问之前移动.

所以我的问题是如何使这个细分市场按预期工作?

完整代码如下:

#include <memory>

struct base {
    virtual ~base() = 0 {}

protected:
    base(std::unique_ptr<base> new_state) :
        previous_state{ std::move(new_state) } {}
private:
    std::unique_ptr<base> previous_state;
};

struct derive_base : base {
    int get_a() const noexcept {
        return a;
    }
protected:
    derive_base(int const new_a, std::unique_ptr<base> new_state) :
        base{ std::move(new_state) }, a{ new_a } {}
private:
    int a;
};

struct final_state : derive_base {
    final_state(std::unique_ptr<base> new_state) :
        derive_base{ dynamic_cast<derive_base&>(*new_state).get_a(), std::move(new_state) } {}
};
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 6

你可以使用构造函数链来修复它:

struct derive : base
{
  private:
    derive(const D& some_data, unique_ptr<X>&& ptr) : base{some_data, std::move(ptr)} {}
  public:
    derive(unique_ptr<X> ptr): derive(func(ptr->some_data), std::move(ptr)) {}
};
Run Code Online (Sandbox Code Playgroud)

原因:正如我在其他答案中所解释的那样,调用func肯定发生在委托构造函数调用之前,而实际移动unique_ptr(而不是仅仅更改其值类别)肯定发生在内部.

当然,这依赖于另一个C++ 11功能,Visual C++可能会或可能没有正确使用.令人高兴的是,自VS2013以来,委托构造函数被列为支持.


更好的办法是始终std::unique_ptr通过引用接受参数,如果您打算从它们中窃取,则通过右值引用.(如果您不会窃取内容,为什么要关心调用者具有哪种类型的智能指针?只需接受原始内容T*.)

如果你用过

struct base
{
    virtual ~base() = 0 {}

protected:
    base(std::unique_ptr<base>&& new_state) :
        previous_state{ std::move(new_state) } {}
private:
    std::unique_ptr<base> previous_state;
};

struct derive_base : base
{
    int get_a() const noexcept {
        return a;
    }
protected:
    derive_base(int const new_a, std::unique_ptr<base>&& new_state) :
        base{ std::move(new_state) }, a{ new_a } {}
private:
    int a;
};

struct final_state : derive_base
{
    final_state(std::unique_ptr<base>&& new_state) :
        derive_base{ dynamic_cast<derive_base&>(*new_state).get_a(), std::move(new_state) } {}
};
Run Code Online (Sandbox Code Playgroud)

你不会在第一时间遇到问题,并且调用者要求完全不变(必须提供rvalue,因为unique_ptr无论如何都是不可复制的)


使其成为通用规则的基本原理如下:按值传递允许复制或移动,无论哪个在呼叫站点更优化.但是std::unique_ptr不可复制,所以实际参数必须是rvalue.