【问题标题】:Pointers, Vector Lists = Mass Confusion指针,向量列表 = 混乱
【发布时间】: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


【解决方案1】:

儿童是vector&lt;Quad&gt; 还是vector&lt;Quad*&gt;?如果是vector&lt;Quad*&gt;,那么这一行是错误的:

Quad *child = &children[i];

因为它将获取指针的地址。那么

child->get_children_recursive(player_pos)

很可能会导致您遇到的错误。

要解决这个问题,只需删除 &amp;

【讨论】:

  • 好吧,那不是你的问题。我们需要寻找其他地方。
  • 还有其他想法吗?我被难住了。
  • 究竟是哪一行导致程序崩溃?
【解决方案2】:
for (int j = 0; j < childs_children.size() - 1; j++)  {

for (int j = 0; j < childs_children.size(); j++)  {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2010-09-23
    • 2018-10-07
    • 1970-01-01
    相关资源
    最近更新 更多