简体   繁体   中英

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. Somewhere I create a vector of this params and need to pass it to Function constructor.

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.

Maybe I miss something pretty simple?

Code snippets

The 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 ?

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

Param is not copyable, because one of its member isn't. Since a vector is as copyable as its contents, then a vector of Param is not copyable.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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