c++ - 有没有办法使 unique_ptr 的实例化不那么冗长?

标签 c++ c++11 unique-ptr

我有一个包含两个 std::unique_ptr 成员的类。我想通过构造函数设置这些成员。

目前我正在这样做:

std::unique_ptr<Assignment> assignment{new Assignment{
       std::unique_ptr<Variable>{new Variable{"a"}},
       std::unique_ptr<Expression>{new Variable{"b"}}
}};

使用常规指针,我会这样做:

auto assignment = new Assignment{new Variable{"a"}, new Variable{"b"}};
delete assignment;

我能否以某种方式使智能指针版本不那么冗长?我希望这样的事情能奏效。

std::unique_ptr<Assignment> assignment{new Variable{"a"},{new Variable{"b"}};

但是,unique_ptr 的构造函数是显式的,所以它不是。

最佳答案

完美的转发构造函数是一个选项吗?

// If you aren't using make_unique, you're doing it wrong.
template <typename T, typename...Args>
inline std::unique_ptr<T> make_unique(Args&&...args) {
    return std::unique_ptr<T>{new T(std::forward<Args>(args)...)};
}

struct Variable {
    std::string name_;

    Variable(std::string name) : name_{std::move(name)} {}
};

struct Assignment {
    std::unique_ptr<Variable> a_, b_;

    template <typename T, typename U>
    Assignment(T&& a, U&& b) :
      a_{make_unique<Variable>(std::forward<T>(a))},
      b_{make_unique<Variable>(std::forward<U>(b))} {}
};

auto assignment = make_unique<Assignment>("a", "b");

大大简化了语法,IMO。

关于c++ - 有没有办法使 unique_ptr 的实例化不那么冗长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21861162/

相关文章:

c++ - 识别微秒范围内的 POSIX 读取暂停

c++ - 关于如何使用 JUCE 托管 VST 插件的教程?

c++ - 为什么需要 ForwardIterators 来建模 DefaultConstructible?

c++ - 是否可以将 lambda 函数用于模板参数?

c++ - 使用模板基类消除工厂类派生类冗余的简洁方法

c++ - std::vector<std::map<uint64_t, std::unique_ptr<double>>> VS2017 编译错误

c++ - 需要帮助来选择实时操作系统和硬件

c++ - const vector 和 const 迭代器之间的区别

c++11 - 所有权和 setter/getter

c++ - vc++ 2010/2012:包含 unique_ptr 的结构的 std::vector 编译器错误