尝试在同一 class 中创建 classes 的向量时出现错误

I get an error when trying to make a vector of classes inside of the same class

我正在尝试用相同 class 的后代制作一个 class 来制作一棵树,但是当我尝试访问向量的某些内容时,它永远不会工作。我得到一个例外:std::length_error 试图访问字符串时。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class A {
  public:
  string name;
  vector<A*> children;
};

int main()
{
    A cl;
    cl.name= "HI!";
    for(int i = 0; i < 10;i++) {
        A newCl;
        newCl.name= "World!";
        cl.children.push_back(&newCl);
    }

    for(int i = 0; i < 10;i++) {
        // error here:
        cout << cl.children[i]->name << endl;
    }

    return 0;
}

有谁知道用 C++ 制作树的更简单方法,或者如何解决这个问题?

问题出在这个循环

for(int i = 0; i < 10;i++) {
        A newCl;
        newCl.name= "World!";
        cl.children.push_back(&newCl);
}

变量 newCl 将在迭代结束时不复存在,您将其地址插入向量中。当您访问它时,您正在访问一个悬空指针,这是未定义的行为,您的程序可能会崩溃、产生垃圾或介于两者之间的任何东西。

您可以按照 Oblivion 的建议使用堆分配,但在这种情况下,您可能需要考虑使用智能指针进行内存管理。

否则,您可以使用值向量 std::vector<A> 而不是指针,这可能来自 C++17(有关更多详细信息,请参阅:

编辑:我在 Chipster 的评论后澄清了 std::vector<A> 的用法。

您将对临时文件的引用存储为 children:

A newCl; 
newCl.name= "World!";
cl.children.push_back(&newCl);

一旦您超出范围,children 就会悬挂。

A* newCl = new A;

应该修复。但是你必须通过向量来释放你的 children.

如果你有理由使用指针,最好使用智能指针:

vector<shared_ptr<A>> children;

Live