boost::lockfree-为排队的元素调用析构函数



我无法强制销毁pop上的boost::lockfree::spsc_queue元素。(当推送覆盖循环缓冲区的元素时,或者当列表被销毁时,即使通过引用访问元素,它们也会被正确销毁)。

我也无法直接访问存储在队列中的元素,以便通过引用销毁它。

#include <boost/lockfree/spsc_queue.hpp>
#include <boost/lockfree/policies.hpp>
#include <iostream>
#include <memory>
using namespace boost::lockfree;
class testDestructor{
        public:
        int x;
        static int y;
        testDestructor(): x(y++){}
        ~testDestructor(){ std::cout << x << std::endl ;}
        };
int testDestructor::y=1;

spsc_queue< std::shared_ptr<testDestructor>, capacity<100>> q;
int sum = 0;
void produce()
{
  for (int i = 1; i <= 100; ++i)
    q.push( std::move( std::shared_ptr<testDestructor>( new testDestructor() ) ) ) ;
}

void consume( std::shared_ptr<testDestructor> & tp){
    sum+=tp->x;
//TRYING TO FORCE DESTRUCTION:
    tp.reset();
}
int main()
{
  produce();
  //consuming a reference to force freeing the pointer
  q.consume_all([](  std::shared_ptr<testDestructor>  & tp){ consume(tp);  });
  std::cout << sum << "<- Destructors should be called before this" << std::endl;
}

旧版本的boost中的spsc_queue存在一些问题。您发布的代码与boost 1.60配合使用效果良好。如果可以,请升级到当前版本。

在Coliru上直播

最新更新