首先,对于这个愚蠢的问题,我深表歉意,但我是 C++ 世界的新手,而且我已经习惯了 Java 和 Python。
我想问一下构造函数在 C++ 中应该如何工作。我希望如果我为我的实例分配一些值或子对象,那么它不会被另一个构造函数删除?
特别是我的问题如下:
我有一个看起来像这样的树类:
class Tree {
Node * const first;
Node * last;
std::vector<Node *> nodesVector;
unsigned int nodes;
public:
Tree(Node * const root) : first(root){
nodes = 1;
nodesVector.push_back(root);
}
}
然后我有一个看起来像这样的 RRTStar 类:
class RRTStar {
Tree * tree;
Node * root;
const double RADIUS;
public:
RRTStar(const Point & point, double radius) : RADIUS(radius){
Node n;
n.point = point;
unsigned int zero = 0;
n.id = zero;
n.cost = 0;
n.parent = NULL;
this->root = &n;
Tree t = Tree(this->root);
this->tree = &t;
}
}
如您所见,从 RRTStar 构造函数调用的 Tree 构造函数中总是会向 vector 附加一个值。当我进行调试时,我可以看到确实将节点 n 添加到 vector 中,但不幸的是,它在 RRTStar 构造函数完成后以某种方式被删除。
所以我的问题是我做错了什么 vector 或者它的树实例的内容被删除了?
最佳答案
这两行看起来最可疑:
this->root = &n;
this->tree = &t;
它们获取局部变量的地址,该变量将在构造函数完成时被销毁。在构造函数之外使用这些指针将是 UB。
您需要使用 new
动态分配它们,并确保您的析构函数、复制构造函数和赋值运算符正确处理它们。
关于c++使用 vector 作为类私有(private)变量时构造函数的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23183870/