简体   繁体   English

在构造函数中使用C ++中的unique_ptr初始化向量

[英]Initialize a vector with unique_ptr in C++ within constructor

I am new to C++, and after having read A LOT about move semantics and unique pointers (and initializer lists), I get why this code won't work (throwing "attempting to reference a deleted function"): 我是C ++的新手,在阅读了很多有关移动语义和唯一指针(以及初始化程序列表)的知识之后,我明白了为什么此代码不起作用(抛出“试图引用已删除的函数”):

term_array::term_array(std::unique_ptr<term>&& opd) 
    : term(std::vector<std::unique_ptr<term>> {std::move(opd)}) {...}

It's a constructor intended to pass a pointer opd (pointing to a term object) on from a derived class term_array to the base class term , where the term constructor expects a vector or pointers. 它是一个构造函数,旨在从派生类term_array传递一个指向基类term的指针opd (指向term对象), term构造函数需要一个向量或指针。 Therefore, I tried to create a std::vector<std::unique_ptr<term>> on the fly and fill it with the one opd pointer received from the term_array constructor. 因此,我试图动态创建一个std::vector<std::unique_ptr<term>> ,并用从term_array构造函数接收到的一个opd指针填充它。 Obviously, this doesn't work since a unique_ptr cannot be copied, and the initializer_list initialization won't allow a move operation. 显然,这是行不通的,因为无法复制unique_ptr ,并且initializer_list初始化将不允许进行移动操作。

I saw in this question how to "list-initialize a vector of move-only type" in regular program flow (meaning when you can use several lines of code). 我在这个问题中看到了如何在常规程序流程中“列表初始化仅移动类型的向量”(意味着何时可以使用多行代码)。 But (how) can this be done within a simple constructor call? 但是(如何)可以在一个简单的构造函数调用中完成? Or am I completely off-track? 还是我完全偏离了轨道?

You can do this with a helper function template: 您可以使用辅助函数模板来执行此操作:

template <class T>
auto SingletonVector(T&& x) {
    std::vector<std::decay_t<T>> ret;
    ret.push_back(std::forward<T>(x));
    return ret;
}

Then: 然后:

term_array::term_array(std::unique_ptr<term>&& opd) 
: term(SingletonVector(std::move(opd))) {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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