【问题标题】:Pass by reference vector gives wrong result通过参考向量传递错误的结果
【发布时间】:2015-06-12 21:07:18
【问题描述】:

所以我想通过调用构造函数来创建一个节点列表,并将节点的地址推送到一个向量(通过引用传递)。我从下面的代码中得到了错误的结果。

#include <iostream>
#include <vector>

using namespace std;

class Node{
    public:
        //Constructor
        Node(int id, vector<Node*> & listNode){
            this->id = id;
            listNode.push_back(this);
        }
        int id;
};

int main(){
    vector<Node*> listNode;

    for(int i=0; i<5; i++){
        Node A(i, listNode);
    }

    for(int i=0; i<5; i++){
        cout<<listNode[i]->id;
    }
}

我期待的输出是:01234
但我得到了 44444。
有没有想过这个错误?

【问题讨论】:

    标签: c++ vector pass-by-reference


    【解决方案1】:

    生命周期是问题的根源。

    您的对象 A 在 for 循环结束后已被销毁。 (例如,在 i=0 创建的 obj A 将在 i 变为 1 时被删除) 但是,向量不知道指针是否不可用。所以指针有一个值指向一个永远不会是 A 的内存的内存。

    【讨论】:

      【解决方案2】:
      for(int i=0; i<5; i++){
          Node A(i, listNode);
      }
      

      A 作用于for 循环,当for 完成时,A 被破坏。 listNode 持有一个悬空指针列表。

      您的代码只有undefined behavior

      增强代码:

      class Node{
          public:
              //Constructor
              Node(int id){
                  this->id = id;
              }
              int id;
      };
      
      vector<Node> listNode;
      
      for(int i=0; i<5; i++){
          listNode.push_back(A(i));
      }
      

      【讨论】:

      • 那么有没有办法让节点不被破坏呢?
      • @jamesalone,这可能是了解newdelete 的好时机。
      • @jamesalone 你可以写new Node (i, listNode); 而不是A(i, listNode);
      猜你喜欢
      • 2014-11-29
      • 2011-04-03
      • 2017-03-14
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2015-01-28
      相关资源
      最近更新 更多