gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:13:21 25 4
gpt4 key购买 nike

我在这里错过了什么?为什么我不能将 vector 作为类构造函数的一部分 move ?从构造函数中删除 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;
}

最佳答案

以下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;
}

我保留了您的其余代码不变,但您可能需要阅读 Why is “using namespace std;” considered bad practice?

关于c++ - 将 unique_ptr 的容器传递给构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com