C++ std::queue::pop() 调用析构函数.指针类型呢?

2022-01-21 00:00:00 queue memory-management c++ std

我有一个 std::queue,它被包装为一个模板类以创建一个线程安全的队列.我有这个类的两个版本:一个存储值类型,一个存储指针类型.

I have a std::queue that is wrapped as a templated class to make a thread-safe queue. I have two versions of this class: one that stores value types, one that stores pointer types.

对于指针类型,我无法在销毁时删除队列中的元素.原因是我不知道如何安全地从队列中移除项目.

For the pointer type, I'm having trouble deleting the elements of the queue on destruction. The reason is that I don't know a way to remove the items from the queue safely.

这个 参考状态(空洞,所以我猜它实际上不是状态它)从队列中删除元素的唯一方法是调用 pop().该参考资料还说 pop() 调用该项目的析构函数.

This reference states (vacuously, so I guess it doesn't actually STATE it) that the only way to remove elements from the queue is to call pop(). The reference also says that pop() calls the destructor for the item.

嗯,这会导致我的指针类型出现问题,因为它们实际上可能指向聚合,也可能不指向聚合.如果其中一个指向聚合,它们都将指向聚合,但由于包装器是模板化的,因此无法保证我们正在处理哪种类型(聚合或非聚合).

Well, this causes problems with my pointer types because they may or may not actually point to aggregates. If one of them points to an aggregate, they all will, but because the wrapper is templated, there is no guarantee which type (aggregated or non-aggregated) we are dealing with.

那么,当 pop() 调用析构函数时,会发生什么?如何确保所有内容都被删除并正确释放内存?

So, when pop() calls the destructor, what happens? How do I ensure that everything is being removed and the memory deallocation properly?

最后,我的解决方案是使用旧版本的 GCC for ARM9.我无法控制这个.我知道有些库有智能指针和容器可以在这里提供帮助,但它们对我来说是禁区.

Lastly, my solution is using an older version of GCC for ARM9. I don't have control over this. I understand that there are libraries that have smart pointers and containers that would assist here, but they are off-limits for me.

推荐答案

在线资源物有所值 - 获得适当的参考,例如 Josuttis 的书.pop() 不会调用析构函数"――它只是通过调用 pop_front() 从队列适配器的底层表示(默认情况下为 std::deque)中删除一个元素.如果被弹出的东西有析构函数,会在被弹出的对象超出范围时使用,但队列类与它无关.

Online sources are worth what you pay for them - get a proper reference like Josuttis's book. pop() does not "call the destructor" - it simply removes an element from the queue adaptor's underlying representation (by default a std::deque) by calling pop_front() on it. If the thing being popped has a destructor, it will be used when the popped object goes out of scope, but the queue class has nothing to do with it.

相关文章