I wasn't able to force destruction of a boost::lockfree::spsc_queue
element on pop. (They are correctly destroyed when a push overwrites an element of the circular buffer or when the list is destroyed, even when accessing the element by reference ).
Neither I was able to direct access to the element stored in the queue for destroying it via a reference.
#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;
}
There are some issues with spsc_queue
in older versions of boost. The code you posted works fine with boost 1.60. Upgrade to the current version if you can.
Live on Coliru