【问题标题】:How to create Quadtree Copy constructor with Recursion如何使用递归创建四叉树复制构造函数
【发布时间】:2013-03-18 18:46:40
【问题描述】:

我正在研究四叉树的复制构造函数。到目前为止,这是我所拥有的:

    //Copy Constructor
    Quadtree :: Quadtree(const Quadtree & other)
    {
    root = copy(other.root);
    resolution = other.resolution;
    }

   //Copy Constructor helper function
    Quadtree::QuadtreeNode *Quadtree :: copy (const QuadtreeNode* newRoot)
    { 
    if (newRoot != NULL)
    {
        QuadtreeNode *node = new QuadtreeNode(newRoot->element);
        node->nwChild = copy(newRoot->nwChild);
        node->neChild = copy(newRoot->neChild);
        node->swChild = copy(newRoot->swChild);
        node->seChild = copy(newRoot->seChild);

        return node;    
    }
    else
        return NULL; 
     }

我不确定我哪里出错了,但是我收到了内存泄漏,Valgrind 指出我有未初始化的值。请帮忙?

附加的是我的 buildTree 函数 - 我实际创建树的地方。我可能在这里做错了什么?

    void Quadtree :: buildTree (PNG const & source, int theResolution)
    {
        buildTreeHelp (root, 0, 0, theResolution, source);  
    }

   void Quadtree :: buildTreeHelp (QuadtreeNode * & newRoot, int xCoord, int yCoord, int d, PNG const & image)
    {
       if (d == 1)
       {
            RGBAPixel pixel = *image(xCoord, yCoord);
            newRoot = new QuadtreeNode(pixel);
            return; 
       }
        newRoot = new QuadtreeNode ();
        newRoot = NULL;

            buildTreeHelp(newRoot->nwChild, xCoord, yCoord, d/2, image);
        buildTreeHelp(newRoot->neChild, xCoord + d/2, yCoord, d/2, image);
        buildTreeHelp(newRoot->swChild, d/2, yCoord + d/2, d/2, image);
        buildTreeHelp(newRoot->seChild, d/2 + xCoord, d/2 + yCoord, d/2, image);
    }

【问题讨论】:

  • 你能发布一个完整的小例子吗?您提供的代码不足以证明内存泄漏或未初始化的访问。
  • 我添加了实际构建树的 buildTree 函数。也许我初始化树的方式有问题?

标签: c++ tree quadtree


【解决方案1】:

我认为内存泄漏在这里:

    newRoot = new QuadtreeNode ();
    newRoot = NULL;

您正在分配内存,然后将指针设置为NULL,而不释放内存。此外,在下一行你试图取消引用你刚刚设置为 NULL 的指针:

    buildTreeHelp(newRoot->nwChild, xCoord, yCoord, d/2, image);

您可能会受益于使用诸如std::unique_ptr 之类的智能指针来管理内存,而不是使用对newdelete 的原始调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2011-05-08
    • 1970-01-01
    • 2020-04-08
    相关资源
    最近更新 更多