将整个 vector 作为元素插入另一个 vector 中。

huangapple go评论76阅读模式
英文:

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&amp;&amp;) and delete default one Person() = delete, but I still get std::unique_ptr&lt;Person,std::default_delete&lt;Person&gt;&gt;::unique_ptr(const std::unique_ptr&lt;Person,std::default_delete&lt;Person&gt;&gt; &amp;)&#39;: 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&lt;std::unique_ptr&lt;Person&gt;&gt;());
    for (const auto&amp; p : v)
    {
        v2[0].push_back(std::move(p));
    }

Code

struct Person
{
    std::string name;
    Person(std::string name) {}
};

    std::vector&lt;std::unique_ptr&lt;Person&gt;&gt; v;
    std::vector&lt;std::vector&lt;std::unique_ptr&lt;Person&gt;&gt;&gt; v2;
    std::unique_ptr&lt;Person&gt; ptr1 = std::make_unique&lt;Person&gt;(&quot;name&quot;);

    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&amp; 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).

huangapple
  • 本文由 发表于 2023年5月25日 06:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定