C++ 移动C+中的列表对象+;指向另一个对象

C++ 移动C+中的列表对象+;指向另一个对象,c++,c++11,C++,C++11,我试图理解这段代码是如何工作的 // 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(){s

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

// 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 obj\n";}
    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 object\n";
      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 Nodes\n";
  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 Nodes\n";
  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;
}
//示例程序
#包括
#包括
#包括
结构复合体
{
int n;
std::字符串str;
复数(intn):n(n),str(“字符串形式”+std::to_String(n)){}
};
结构体类型
{

Node(){std::cout我看到一个
节点m
正在生成,它包含两个空列表。列表1包含int,列表2包含int和字符串。然后调用函数CreateNode时,它只需遍历空节点并逐个赋值(请参阅create Node函数)(本可以为此使用循环,但在这个实现中,他们只是一个接一个地推送(相同的事情)),然后打印值


我希望这有助于欢呼。

我看到一个
节点m
正在生成,其中包含两个空列表。列表1包含int,列表2包含int和字符串。然后调用函数CreateNode时,它只需遍历空节点并逐个赋值(请参阅create Node函数)(本可以为此使用循环,但在这个实现中,他们只是一个接一个地推送(相同的事情)),然后打印值

我希望这有助于干杯。

那是因为

顺便说一下,通过使用初始值设定项列表,可以稍微改进move构造函数:

Node(Node&& n) : ll{std::move(n.ll)}, pll{std::move(n.pll)} {}
这将移动构造两个列表(使用
std::list
的移动构造函数),而不是默认构造然后移动分配它们。复制构造函数也是如此。

这是因为

顺便说一下,通过使用初始值设定项列表,可以稍微改进move构造函数:

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

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

封装是神奇的。有时它是黑暗魔法。封装是神奇的。有时它是黑暗魔法。