2
\$\begingroup\$

I have decided to make small ObjectPool class for internal use. What do you think about it ?

template<class T>
class ObjectPool
{
public:
    inline T& getObject();
    inline void releaseObject(T& obj);
private:
    std::stack<std::reference_wrapper<T>> mFree;
    std::vector<T> mPool;
};

template<class T>
void ObjectPool<T>::releaseObject(T& obj)
{ 
    mFree.push(obj);
}

template<class T>
T& ObjectPool<T>::getObject()
{
    if (mFree.size()) {
        T& num = mFree.top();
        mFree.pop();
        return num;
    } else {  
        mPool.emplace_back();
        return mPool.back();
    }
}

I also want to make all function and data static. Is that considered a bad practice?

\$\endgroup\$
2
\$\begingroup\$

First of all, free references will be invalidated each time mPool resizes. Which will lead to all sorts of undefined behavior.

Resizing pool is not a great idea in terms of performance, too. Better have constant size chunks, and add more chunks if needed.

Such a pool implies your user is no more able to get benefits of RAII, which can be a huge loss.

For your question about static methods. It is not a bad practice per se, but your user will no longer be allowed to use different pools for the same type. If you want to make a static method, you better have strong argument to do so.

Overall, consider to use containers+allocators instead of pool.

\$\endgroup\$
  • 1
    \$\begingroup\$ i completely agree with @GeniusIsme, although it's not clear to me exactly how to mess around with allocators. however, if your life depended on it, and for things like polymorphic objects (and if you don't care about things like locality of reference, etc.), i guess you could use pointers or even better smart pointers with your containers. see this and that \$\endgroup\$ – compor Feb 13 '15 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.