【发布时间】:2012-08-22 07:37:35
【问题描述】:
如果你能建议一个更合适的标题,我会永远欠你的。
问题:我有一个本质上是递归的函数,它旨在从每个四边形中获取每个孩子并将其返回给原始调用者。问题是我每次运行程序时都会得到以下信息(在我的控制台窗口中):
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
我的目标是检索每个孩子作为指针。
来电者如下:
std::vector<Quad*> children = root->get_children_recursive(player_pos);
这是函数本身:
std::vector<Quad*> Quad::get_children_recursive(glm::vec3 player_pos) {
std::vector<Quad*> out_children;
if (children.size() != 0) {
for (int i = 0; i < children.size(); i++) {
Quad *child = &children[i];
std::vector<Quad*> childs_children = child->get_children_recursive(player_pos);
for (int j = 0; j < childs_children.size() - 1; j++) {
Quad *childs_child = childs_children.at(j);
out_children.emplace_back(childs_child);
}
}
}
if (this->should_draw(player_pos)) {
out_children.emplace_back(this);
}
return out_children;
}
如果您希望我提供更多代码或任何其他详细信息,我将非常乐意提供。
(每次我尝试使用调试器并且程序到达导致上述错误的行时,我都会收到 BSOD :O)
编辑:
标题:
class Quad {
public:
...
std::vector<Quad*> get_children_recursive(glm::vec3 player_pos);
...
protected:
private:
...
std::vector<Quad> children;
...
};
【问题讨论】:
-
既然你在这里处理指针,使用
emplace_back是没有意义的。 -
请记住,当您有一个指针向量时,如果您调用 new 将其添加到所述向量,则需要在每个条目上调用 delete。阻止内存泄漏,但这是 Vasilev 描述的内存访问冲突
-
只是备注:按节点填充结果不是很可扩展。通过引用传递结果容器可能会更好,因此它只填充一次。此外,如果您无法猜测结果容器的最大使用量,则 std::deque 可能更合适。
-
@BjornPollex 为什么使用 emplace_back 没有意义?请解释一下,我是 C++ 新手。此外,我从不在任何向量上使用“新”。
-
@Darestium:
emplace_back用于直接在向量中构造一个对象,而不是复制一个对象(这是push_back所做的)。有了指针,两者是等价的。
标签: c++ pointers stdvector dynamic-memory-allocation