将变量分配给动态分配的返回值?

时间:2015-09-26 02:42:41

标签: c++

我正在尝试将变量赋值给返回值,但在将值分配给pq之前调用解构函数。我还得到以下错误,我假设是尝试双重删除变量:

_BLOCK_TYPE_IS_VALID(pHead-> nBlockUse)

    PriorityQueue pq;
    pq = FindThroughPaths(a, b);

FindThroughPaths(a,b)返回PriorityQueue。

我可能会收到此错误,因为返回值已动态分配成员变量。

我只是想找到一种方法来保持FindThroughPaths(a,b)的返回值在范围内,并且我不想创建多个实例来访问它的成员。这是我想要的一个例子:

    PriorityQueue pq;
    pq = FindThroughPaths(a, b);
    while (!pq.IsEmpty) {
         Path tmp = pq.Dequeue();
         std::cout << "\n" << tmp.name << " #" << tmp.number;
    }

PriorityQueue的构造函数,解构函数和赋值运算符:

    PriorityQueue::PriorityQueue()
    {
            std::cout << "\nConstructor called." << endl;
            items.elements = new ItemType[maxItems];
            length = 0;
    }


    PriorityQueue::~PriorityQueue()
    {
           std::cout << "\nDeconstructor called." << endl;
           delete[] items.elements;
    }

    PriorityQueue PriorityQueue::operator=(const PriorityQueue &originalPQ)
    {
           //This function is started after the return value, the right operand, has been deconstructed.
           std::cout << "\nAssignment called." << endl;
           for (int i = 0; i < maxItems; i++)
                   items.elements[i] = originalPQ.items.elements[i];
           return *this;
     }

1 个答案:

答案 0 :(得分:0)

如果不查看从PriorityQueue方法返回FindThroughPaths的方式,很难确切地说出问题是什么,但很可能问题是您错过了复制PriorityQueue类中的构造函数。

PriorityQueue::PriorityQueue(const PriorityQueue &other)
{
    std::cout << "\nCopy constructor was called" << endl;
    // there are better ways to implement this, but I think this will correctly
    // defer to the assignment operator you wrote
    *this = other;
}

从方法返回对象时,将调用复制构造函数来构建将返回的对象。如果您尚未实现复制构造函数,那么将使用默认实现,并且在您的情况下该默认实现是不够的。

仍将调用析构函数来销毁FindThroughPaths方法本地的PriorityQueue对象。

您可能会发现this other question有关从方法中返回对象的帮助。

相关问题