Passing a container of unique_ptr to constructor?
c++, constructor, containers, move, unique-ptr
Solution
The following should compile fine:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Bar
{
public:
Bar(vector<unique_ptr<char>> vec);
vector<unique_ptr<char>> vec_;
};
Bar::Bar(vector<unique_ptr<char>> vec) : // If you intend to move something,
// do not make it const, as moving
// from it will in most cases change
// its state (and therefore cannot be
// const-qualified).
vec_(move(vec))
{
}
int main()
{
vector<unique_ptr<char>> vec;
vec.push_back(unique_ptr<char>(new char('a')));
vec.push_back(unique_ptr<char>(new char('b')));
vec.push_back(unique_ptr<char>(new char('c')));
vector<unique_ptr<char>> vec1 (move(vec));
Bar bar(std::move(vec1)); // Just like the line immediately above,
// the explicit `move` is required, otherwise
// you are requesting a copy, which is an error.
return 0;
}
I have left the rest of your code unchanged, but you may want to read Why is “using namespace std;” considered bad practice?
Problem
What am I missing here? Why can't I move a vector as part of class constructor? Removing const from the constructor doesn't help either. ``` #include <iostream> #include <vector> #include <memory> using namespace std; class Bar { public: Bar(const vector<unique_ptr<char>> vec); vector<unique_ptr<char>> vec_; }; Bar::Bar(const vector<unique_ptr<char>> vec) : vec_(move(vec)) //not ok { } int main() { vector<unique_ptr<char>> vec; vec.push_back(unique_ptr<char>(new char('a'))); vec.push_back(unique_ptr<char>(new char('b'))); vec.push_back(unique_ptr<char>(new char('c'))); vector<unique_ptr<char>> vec1 (move(vec)); //ok Bar bar(vec1); return 0; } ```