英文:
Insert the whole vector<unique_ptr> as element in other vector
问题
I tried to define move constructor Person(Person&&)
and delete the default one Person() = delete
, but I still get std::unique_ptr<Person,std::default_delete<Person>>::unique_ptr(const std::unique_ptr<Person,std::default_delete<Person>>&)'': attempting to reference a deleted function
.
I tried to manually iterate and move one item at a time, but this didn't help. What am I missing here?
Attempt
v2.push_back(std::vector<std::unique_ptr<Person>>());
for (const auto& p : v)
{
v2[0].push_back(std::move(p));
}
Code
struct Person
{
std::string name;
Person(std::string name) {}
};
std::vector<std::unique_ptr<Person>> v;
std::vector<std::vector<std::unique_ptr<Person>>> v2;
std::unique_ptr<Person> ptr1 = std::make_unique<Person>("name");
v.push_back(std::move(ptr1));
v2.push_back(v);
英文:
I tried to define move constructor Person(Person&&)
and delete default one Person() = delete
, but I still get std::unique_ptr<Person,std::default_delete<Person>>::unique_ptr(const std::unique_ptr<Person,std::default_delete<Person>> &)': attempting to reference a deleted function
.
I tried to manually iterate and move one item at a time, but this didn't help. What am I missing here?
Attempt
v2.push_back(std::vector<std::unique_ptr<Person>>());
for (const auto& p : v)
{
v2[0].push_back(std::move(p));
}
Code
struct Person
{
std::string name;
Person(std::string name) {}
};
std::vector<std::unique_ptr<Person>> v;
std::vector<std::vector<std::unique_ptr<Person>>> v2;
std::unique_ptr<Person> ptr1 = std::make_unique<Person>("name");
v.push_back(std::move(ptr1));
v2.push_back(v);
答案1
得分: 3
以下是翻译好的部分:
第一个问题是在你的两段代码中都存在的:
for (const auto& p : v)
{
v2[0].push_back(std::move(p));
}
去掉 const
- 你不能从一个 const
对象(或引用)中移动。
和:
v2.push_back(v);
会尝试复制 v
(由于 unique_ptr
的特性,这是不允许的),所以应该改成:
v2.push_back(std::move(v));
(假设这是你的意图)。
英文:
There are two issues here, one in each of your code snippets:
for (const auto& p : v)
{
v2[0].push_back(std::move(p));
}
Get rid of the const
- you can't move from a const
object (or reference).
And:
v2.push_back(v);
will try to copy v
(which you can't do, because of the unique_ptr
aspect), so it needs to be:
v2.push_back(std::move(v));
(assuming that is your intent).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论