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?

asked Feb 12, 2015 at 19:37
\$\endgroup\$

1 Answer 1

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.

answered Feb 13, 2015 at 8:28
\$\endgroup\$
1
  • 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\$ Commented Feb 13, 2015 at 9:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.