Search code examples
c++c++11memoryc++17unique-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 Params. 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_ptrs, 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&)'


Solution

  • 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)) {}