1

我正在尝试使用模板化对象池,但无法重载放置新运算符。new 运算符适用于默认构造函数,但不适用于非默认构造函数。我在这里粘贴我的简单代码。

#include <boost/pool/object_pool.hpp>
#include <cstddef>

template<typename T>
class objectPool
{
    public:
        void* operator new (std::size_t num) { void *vp = _pool.malloc(); T *t = ::new(vp)T; return t; }
        void* operator new[] (std::size_t num) { void *vp = NULL; assert(0); return vp; }
        void operator delete (void *vp) { _pool.free(static_cast<T*>(vp)); return; }
        void operator delete [] (void *vp) { assert(0); return; }

    private:
        static boost::object_pool<T> _pool;
};

template<typename T>
boost::object_pool<T> objectPool<T>::_pool;

class number : public objectPool<number>
{
    long long _value1, _value2;
    public:
    number(long long value1, long long value2) : _value1(value1), _value2(value2) { return; }
    ~number(){ return; }
    void print() { std::cerr<<"_value1:"<<_value1<<"_value2:"<<_value2; return; }
};

int
main(int ac, char **av)
{
    number *n = new number(1000, 2000);
    n->print();
    delete n;
    return 0;
}
4

1 回答 1

3

运算符new不调用构造函数,它分配内存http://www.cplusplus.com/reference/new/operator%20new/

当你使用它时,构造函数被调用:

//normal new
new T(a1, a2);
//placement new
new (na1, na2) T(a1, a2)

你应该在你的new运营商中删除新的电话并返回vp

于 2013-03-29T13:48:50.763 回答