简体   繁体   English

具有 unique_ptr 的结构向量

[英]Vector of structs with unique_ptr

I've already read many answers for the similar questions, but still cannot find a solution for my problem.我已经阅读了许多类似问题的答案,但仍然找不到我的问题的解决方案。

I have the struct:我有结构:

struct Param {
    std::string name;
    std::unique_ptr<Object> default_val;
};

I have the class Function that stores a vector of Param s.我有存储Param向量的 class Function Somewhere I create a vector of this params and need to pass it to Function constructor.我在某个地方创建了这个参数的向量,并需要将它传递给Function构造函数。

The problem is in the moment when I'm trying to pass vector to constructor.问题出在我试图将向量传递给构造函数的那一刻。 I know that I need to move all unique_ptr s, and I do it.我知道我需要移动所有unique_ptr ,我就这样做了。

Maybe I miss something pretty simple?也许我错过了一些非常简单的东西?

Code snippets

The Function : Function

using Params = std::vector<Param>;

class Callable : public Object {
public:
    Callable(const Params & params) : params(params) {}
// ...
private:
    Params params;
}

The code where I create vector:我创建向量的代码:

Params params;
for(auto & p : func_decl->params){
    auto default_val = eval(p.default_val.get());
    Param p(p.id->get_name(), std::move(default_val));
    params.push_back(std::move(p));
}

Is it possible not to use here shared_ptr ?是否可以不在这里使用shared_ptr

The output is: error: use of deleted function 'Param::Param(const Param&)' output 是: error: use of deleted function 'Param::Param(const Param&)'

Param is not copyable, because one of its member isn't. Param是不可复制的,因为它的一个成员不是。 Since a vector is as copyable as its contents, then a vector of Param is not copyable.由于向量与其内容一样可复制,因此Param的向量不可复制。

When you do this:当你这样做时:

Callable(const Params & params) : params(params) {}

You're trying to use vector's copy constructor .您正在尝试使用向量的复制构造函数 That won't compile.那不会编译。

You'll need to instead move the input vector, which will move its contents at the same time.您需要移动输入向量,这将同时移动其内容。 That means changing the constructor so it takes an rvalue reference, and also use std::move to move the vector.这意味着更改构造函数,使其采用右值引用,并使用std::move移动向量。

Callable(Params&& params) : params(std::move(params)) {}

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

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