Programmer
Programmer

Reputation: 8717

boost::lockfree::queue as static data member

We have a class where we declare boost::lockfree::queue as static data member and override new and delete operator. The logic in the new / delete operator is to create an instance of class to get / put pointer of an object in the queue.

The issue is that after the test cases finishes which is success I get segment fault. If I comment the delete arr[i] statement out there fault no longer occurs.

My assumption is that cause the Boost queue is static hence the data member will be destroyed last or its own destructor would be called when program is to end but then I am not sure what is in its destructor that causes the abort or gives segmentation fault.

Any pointers would be really helpful to resolve the issue?

Upvotes: 0

Views: 313

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136266

You need to be aware that operator new and new expression (e.g. new B()) are different things. The new expression invokes the corresponding operator new and then the constructor of the object. The job of operator new is to return uninitialised memory, the object does not exist at that point.

When you call f->initialize(); in operator new implementation, that call is then followed by the constructor of the object, which must initialise all object's memory.

In other words, you can only implement memory cache in operator new, not object cache.

If you want a cache of objects you need to use a factory (factory design pattern).

Have a look at boost::pool to get started.

Upvotes: 2

Related Questions