c++ - 通过引用 vector 给出错误的结果

标签 c++ vector pass-by-reference

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

#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。
对这个错误有什么想法吗?

最佳答案

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

A 的作用域为 for 循环,当 for 结束时,A 被破坏。 listNode 保存一个悬空指针列表。

您的代码只是有未定义的行为

增强代码:

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));
}

关于c++ - 通过引用 vector 给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505653/

相关文章:

c++ - 我的数组是导致 CPU 和内存快速增加的原因吗?

c++ - 如何在 visual studio 中保存默认启动项目

c++ - 如何在 C++ 中的映射中存储地址?

c++ - 使用 Visual Studio Shell(独立)2015 编译

c++ - 计算 3D 对象和点之间的角度

c++ - Release模式下迭代器的绑定(bind)检查 (c++)

C 字符串传递

c++ - 对象数组

properties - 经典 ASP - 将属性作为 byref 传递

c++ - 作为 `const&`轻量级对象传递