c++ - 从指针返回对象时意外的析构函数调用

标签 c++ pointers return destructor

我正在尝试将我在 C# 中创建的优先级队列实现重新创建为 C++,作为一个项目以跳入 C++,但是很多细微差别让我感到困惑。队列被设计为可在任何给定类 T 上工作的模板。队列将明确地使用表示称为优先级对的对象的结构:指向 T 对象的指针和关联的优先级值 (int)。

这样做的目的是让队列中被比较的实际对象(T's)完全独立并且只被指向。我可能并不明确需要该结构来完成此操作,但这就是我的做法。

队列实现中的重要部分:

template <class T>
class PriorityQueue
{
public:
    PriorityQueue(const int maxSizeIn)
    {
        maxSize = maxSizeIn;
        queueArray = new PriorityPair<T>*[maxSize];
        currentHeapSize = 0;
    }
    ~PriorityQueue()
    {
        cout << "Destroy Queue with size: " << currentHeapSize << endl;
        for (int i = 0; i < currentHeapSize; i++)
        {
            delete (PriorityPair<T>*)queueArray[i];
        }
        delete[] queueArray;
}
private:
    PriorityPair<T>** queueArray;

PriorityPair 的结构:

template <class T>
struct PriorityPair
{
    PriorityPair(int valueIn, T* objectIn)
    {
        _PriorityValue = valueIn;
        _Object = objectIn;
    };

    ~PriorityPair()
    {
         cout << "Destroy Pair for object :(" << *_Object << "):  << endl;
    }

    int _PriorityValue;
    T* _Object;
};

在我的测试过程中,我发现调用我的 PeekTop 方法似乎会导致调用 PriorityPair 的析构函数。我最好的猜测是,由于未能理解该语言的一些细微差别,我不小心创建了一个临时的。

这是查看方法:

    T PeekTop()
    {
        if (IsEmpty())
            return nullptr;
        else
            return *((PriorityPair<T>)(*queueArray[0]))._Object; 
    }

此外,这是插入操作(最低效插入,不进行堆/队列操作):

    int InsertElement(PriorityPair<T>* elementIn)
    {
        //do not insert nulls --
        if (elementIn == nullptr)
            return -2;
        //we could user std::vector or manually expand the array, but a hard max is probably sufficient
        if (currentHeapSize == maxSize)
        {
            return -1;
        }
        //insert the pointer to the new pair element in at the index corresponding to the current size, then increment the size
        queueArray[currentHeapSize++] = elementIn;
        return 0;
    }

我主要有以下内容:

PriorityQueue<string> queue = PriorityQueue<string>(10);
string s1 = "string1";
int code = queue.InsertElement(new PriorityPair<string>(5, &s1));
string i = queue.PeekTop();
cout << "-------\n";
cout << i << endl;

这似乎有效,因为它确实正确插入了元素,但我不明白那对新元素是否按照我的预期运行。当我运行代码时,我的优先级对的析构函数被调用了两次。这在调用函数 PeekTop 时特别发生。一次在队列的生命周期内,一次在队列超出范围并被销毁时。

这是上面代码的输出:

Code: 0
Destroy Pair for object :(string1): with priority :(5):
-------
string1
Destroy Queue with size: 1
Destroy Pair for object :(): with priority :(5):

第一个析构函数调用正确地显示了字符串及其值,但在第二个中我们可以看到字符串本身已经超出范围(这很好并且符合预期)。

最佳答案

除了以下划线开头的名称(正如人们在评论中指出的那样)之外,您的问题似乎在 return *((PriorityPair<T>)(*queueArray[0]))._Object 行中.让我们从内到外逐一审视这个问题。

queueArrayPriorityPair<T>** ,如 PriorityQueue 中声明的那样.这可以理解为“指向 PriorityPair<T> 的指针” ”,但在您的情况下,您的意思是“指向 PriorityPair<T> 的原始指针数组” ”,这也是一个有效的阅读。到目前为止一切顺利。

queueArray[0]PriorityPair<T>*& ,或“对指向 PriorityPair<T> 的指针的引用” ”。引用在 C++ 中是完全不可见的,这仅意味着您处理的是数组的实际第一个元素,而不是拷贝。同样,在试图查看队列顶部时,这是一个合理的要求。

*queueArray[0]只是一个PriorityPair<T>& ,或“引用 PriorityPair<T> ”。同样,此处的引用仅意味着您正在处理 queueArray[0] 指向的实际内容,而不是拷贝。

(PriorityPair<T>)(*queueArray[0])PriorityPair<T> ,将您已经拥有的那个转换到一个新的结果。 这会创建一个临时的 PriorityPair<T> ,这是您稍后看到的被摧毁的。没有编程理由进行此强制转换(您的 IntelliSense 问题是一个不同的问题,我对 VS 的了解还不够,无法对它们发表评论);它已经是正确的类型。如果您添加 this,您可以验证它是不同的被销毁的到输出,因为 this是指向当前对象的指针,临时对象需要存在于内存中的其他地方。

((PriorityPair<T>)(*queueArray[0]))._ObjectT* , 或“指向 T 的指针”。事实上,它指向T。存储在优先级队列的顶部,这很好。

最后,完整的表达式 *((PriorityPair<T>)(*queueArray[0]))._Object取消引用以给出 T ,返回语句返回一个 拷贝 T .这不会影响您看到的行为,但如果您将析构函数调用添加到您测试的对象,它会。返回对 T 的引用可能会更有效,这将放弃复制,通过更改 T 的返回类型至 T&T const& .

我注意到的与此问题无关的其他问题,您在学习 C++ 时可能会发现它们很有用(不是一个完整的列表;我主要不是在寻找这些):

  • 你的两个构造函数都应该使用 initializer lists并且有空体(是的,new 表达式可以放在初始化器列表中,我想几乎所有与我交谈过的人都是第一次问这个问题或假设不正确,包括我)。这会更有效,也更地道。
  • 您不需要为 PriorityPair 实现析构函数(学习语言的细微差别除外);这就是所谓的普通旧数据 (POD) 类型。如果你想要 PriorityPairdelete 的破坏T你会需要它,但你想要 T完全分开管理。
  • 正如人们在评论中指出的那样,you aren’t allowed to use those identifier names yourself如果编译器或标准库需要它们。这可能没问题,它可能会在编译时给您带来问题,或者它可能看起来工作正常但发送所有用户的浏览器历史和电子邮件给他们的 parent 和/或雇主。最后一个不太可能,但 C++ 标准并不禁止它;这就是未定义行为的含义。其他允许的行为包括制造黑洞以摧毁地球和 shooting demons out of your nose ,但在实践中这些可能性更小。
  • 认为您拥有PriorityQueue 的析构函数逻辑正确的,而且很容易把这种事情搞砸。恭喜!

关于c++ - 从指针返回对象时意外的析构函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42821639/

相关文章:

C - 通过引用传递?

android - Android不在ACTION_DOWN状态时如何获取鼠标指针位置

c++ - 源文件中的 Typedef 私有(private)结构原型(prototype)

c++ - 在 Mac 上使用 PJSIP 进行回声消除

c++ - dynamic_cast 上的 SIGSEGV

object - 安卓 : problem retrieving bitmap from database

c++ - 为什么我的 while 循环结束了?

c++ - 警告 : address of local variable 'angles' returned [-Wreturn-local-addr]

c++ - 未记录的 C++ 预处理器指令 (MSVC 2013u4)

android - -Werror,-Wundefined-inline 是什么意思?