将 unique_ptr 的容器传递给构造函数?

Agr*_*hak 5 c++ containers constructor move unique-ptr

我在这里缺少什么?为什么我不能将向量作为类构造函数的一部分移动?从构造函数中删除 const 也没有帮助。

#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;
}
Run Code Online (Sandbox Code Playgroud)

use*_*016 5

以下内容应该可以正常编译

\n\n
#include <iostream>\n#include <vector>\n#include <memory>\n\nusing namespace std;\n\nclass Bar\n{\npublic:\n  Bar(vector<unique_ptr<char>> vec);\n  vector<unique_ptr<char>> vec_;\n};\n\nBar::Bar(vector<unique_ptr<char>> vec) : // If you intend to move something,\n                                         // do not make it const, as moving\n                                         // from it will in most cases change\n                                         // its state (and therefore cannot be\n                                         // const-qualified).\n  vec_(move(vec))\n{\n}\n\nint main()\n{\n  vector<unique_ptr<char>> vec;\n  vec.push_back(unique_ptr<char>(new char(\'a\')));\n  vec.push_back(unique_ptr<char>(new char(\'b\')));\n  vec.push_back(unique_ptr<char>(new char(\'c\')));\n  vector<unique_ptr<char>> vec1 (move(vec));\n  Bar bar(std::move(vec1)); // Just like the line immediately above,\n                            // the explicit `move` is required, otherwise\n                            // you are requesting a copy, which is an error.\n  return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我保留了其余代码不变,但您可能想阅读Why is \xe2\x80\x9cusing namespace std;\xe2\x80\x9d 被认为是不好的做法?

\n