views:

124

answers:

2

I'd like to use boost.pool. It's okay if you don't know about it. Basically, it has two main functions, malloc() and free().

I've overloaded new and delete for my custom defined class test.

class test
{
public:

    test()
    {
        cout    << "ctor" << endl;
    }

    ~test()
    {
        cout    << "dtor" << endl;
    }

    void*   operator new(size_t) throw()
    {
        cout    << "custom operator new" << endl;
        return _pool.malloc();
    }

    void    operator delete(void* p)
    {
        cout    << "custom operator delete" << endl;
        _pool.free(p);
    }

    void    show()
    {
        cout    << _i << endl;
    }

private:
    int _i;
    static boost::pool<>    _pool;
};// class test

boost::pool<>   test::_pool(sizeof(test));

When I create instance of test using new, constructor was not called but if I delete it, destructor was called. Why? and can I avoid it?

A: 

Could it be because the global operator new is getting called? Anyways, just a comment about your class...

operator new and operator delete are always static (even if you don't write the keyword), so it's good practice to use static in the declaration.

You declared operator new with throw(), meaning that it won't throw. But you use a statement (iostreaming) that can throws. Maybe you should surround that with try/catch and create an std::nothrow_t version.

dudewat
+1  A: 

Can't reproduce, when added

#include <iostream>
#include <boost/pool/pool.hpp>
using namespace std;

(why do people omit such things that are necessary to make the code compile?!) and

int main()
{
    test* p = new test;
    delete p;
}

This is either a stripped-down and modified version that doesn't have that behavior or your compiler may be broken (which version is it?)

In any case your aim should be getting the constructor called, rather than getting destructor not called. Overloaded operator new just deals with raw memory allocation, the built-in new-expression should use that to obtain the memory and then call the constructor to create an instance there.

Edit: the only way I can reproduce your output is by circumventing the built-in new-expression:

test* p = static_cast<test*>(test::operator new(sizeof (test)));
UncleBens