我有以下问题: 我在课堂树这个方法:C++返回,而不是它全局实例变量的副本
Node * nearest(const Point & point) const{
double minDistance = numeric_limits<double>::max();
Node * nearest = new Node;
for(Node *n : nodesVector){
int actualDistance = point.distance(n->point);
if(minDistance > actualDistance){
nearest = n;
minDistance = actualDistance;
}
}
return nearest;
}
这种方法是从另一个类调用如下:
void extend(const Point & rand){
Node *xNear = this->tree.nearest(rand);
Node *xRand = tree.add(rand, xNear);
std::vector<Node *> xNearSet = tree.rNearest(rand, this->RADIUS);
for(Node *node : xNearSet){
double c = node->cost + node->point.distance(rand);
if(c < xRand->cost){
xRand->parent = node;
}
}
for(Node *node : xNearSet){
double c = xRand->cost + node->point.distance(rand);
if(c < node->cost){
node->parent = xRand;
}
}
}
我需要我的方法最接近并扩展到扩展执行后不改变树中的变量,特别是最近的节点。
所以我认为使用指针会为我做这件事,但不幸的是它没有,所以我试图创建新的指针节点,但这种方法也不适合我。
我想问一下,我怎样才能实现它不改变原来的节点(只使用它的副本,将不被视为本地变量或引用原来的那个)最近使用?
非常感谢您的任何建议。
编辑: 也许我会稍微改写一下这个问题。现在,我已删除了内存泄漏,该行:
Node * nearest = new Node;
一行:
Node * nearest = nullptr;
但主要问题是,现在仍然是局部变量节点后* xNear消失再有奇怪的值分配给最靠近的原始节点。
“最近”的代码调用'new'并覆盖存储的变量 - > MEMORY LEAK。 – laune
如果你用'new()'创建类实例,你应该决定哪个类应该保存它们,或者使用[** smart pointers **](http://en.cppreference.com/w/cpp/memory)来管理内存取消/分配给你。 –
以前关于内存管理的评论是关注的。现在,如果你想要一个被指向的对象的副本,那么你将不得不创建一个。 (根据定义,指针指向原始对象)。例如,如果您想处理由'nearest'返回的值的副本,则需要沿着'Node copiedNode = * x近似;' – Lilshieste