将列表的对象C++移动到另一个对象

Moving object of lists in C++ to another object

本文关键字:一个对象 移动 C++ 列表 对象      更新时间:2023-10-16

我试图理解这段代码是如何工作的。

// Example program
#include <iostream>
#include <string>
#include <list>
struct complex
{
int n;
std::string str;
complex(int n): n(n), str("String form " + std::to_string(n)) {}
};
struct Node
{
Node(){std::cout<<"creating objn";}
Node(const Node &a){ll = a.ll; pll = a.pll;}
Node(Node &&a){ll = std::move(a.ll); pll = std::move(a.pll);}
Node& operator=(const Node &a){ll = a.ll; pll = a.pll; return *this;}
Node& operator=(Node &&a){ll = std::move(a.ll); pll = std::move(a.pll); return *this;}
~Node()
{
std::cout<<"Destroying objectn";
for(auto iter : ll)
{
iter = 0;
}
for(auto iter : pll)
{
delete(iter);
iter = nullptr;
}
}
std::list<int> ll;
std::list<complex*> pll;
};
Node CreateNode()
{
Node n;
n.ll.push_back(1);
n.ll.push_back(2);
n.ll.push_back(3);
n.ll.push_back(4);
n.ll.push_back(5);
n.ll.push_back(6);
n.ll.push_back(7);
n.pll.push_back(new complex(11));
n.pll.push_back(new complex(21));
n.pll.push_back(new complex(31));
n.pll.push_back(new complex(41));
n.pll.push_back(new complex(51));
n.pll.push_back(new complex(61));
n.pll.push_back(new complex(71));
return std::move(n);
}
int main()
{
Node m;
std::cout<<"Before assigning Nodesn";
for(auto iter : m.ll)
{
std::cout<<iter<<" ";
}
std::cout<<"n";
for(auto iter : m.pll)
{
std::cout<<iter->n<<", "<<iter->str<<" --> ";
}
std::cout<<"n";
m = CreateNode();
std::cout<<"After assigning Nodesn";
for(auto iter : m.ll)
{
std::cout<<iter<<" ";
}
std::cout<<"n";
for(auto iter : m.pll)
{
std::cout<<iter->n<<", "<<iter->str<<" --> ";
}
std::cout<<"n";
return 0;
}

在复制构造函数或复制赋值运算符中,我只是传递具有离散内存分配的列表。在我的移动语义中只传递a.pll怎么可能将整个内存移动到下一个对象?我希望我需要遍历每个列表对象,然后移动它们。

但是没有。它只是像魔术一样工作,只需将a.pll移动到其他对象即可。内部情况如何?

您可以在此处看到此操作: https://repl.it/repls/WildComfortableLesson

那是因为std::list为您实现了移动分配。

顺便说一下,可以使用初始值设定项列表对移动构造函数进行一些改进:

Node(Node&& n) : ll{std::move(n.ll)}, pll{std::move(n.pll)} {}

这将移动构造两个列表(使用std::list的移动构造函数(,而不是默认构造,然后移动分配它们。复制构造函数也是如此。

我看到正在制作一个包含两个空列表的Node m。列表 1 包含整数 列表 2 包含一个 int 和字符串。然后,当您调用函数 CreateNode 时,它只是遍历空节点并逐个分配值(请参阅创建节点函数((本可以为此使用循环,但在此实现中它们只是逐个推送(同一件事((。然后他们打印值。

我希望这有助于欢呼。