# C++ Object Pool

## Recommended Posts

Hi!

I wrote object pool. This is single-header library for fast object allocation. All objects inside of the pool placed in a contiguous memory block to be cache-friendly. Detailed description is in repository.

Here is some examples:

class Foo {
private:
int fooBar;
public:
Foo() {}
Foo(int foobar) : fooBar(foobar) {}
};

...

Pool<Foo> pool(1024); // make pool with default capacity of 1024 objects
Handle<Foo> bar = pool.Spawn(); // spawn object with default constructor
Handle<Foo> baz = pool.Spawn(42); // spawn object with any args

// do something

// return object to pool
pool.Return(bar);
pool.Return(baz);

Results of tests are in attached files.

Please, criticize it and give me some feedback.

##### Share on other sites

You currently use a global stamp counter. That will overflow relatively quickly (still an eternity but whatever).

I believe what you want, instead, is to increment the stamp of each container slot independently. Comparison of two stamps should be valid only if index is equal - so its ok if two indices have the same stamp. So stamps are per-index.

With the global counter, IsValid can start returning false positives as soon as you do 32^2 insertions over the entire container (which is a problem if the pool has many objects in it - the insertions will add up).

With per-index counters, you will only get the problem if all those insertions are to the exact same index/slot. If theyre spread over the entire container (as they naturally should be), the stamp counters will keep incrementing slowly (minimizing chance of bugs from IsValid false positives).

The real benefit is that you can switch to 1 or 2 byte stamps (I recall someone using 2 bytes) and it should still take forever for potential ambiguity to occur (tens of thousands of reuses of the exact same index, before the first stamps get reused). With current global stamp that wouldnt be safe (the counter would wrap around way too quickly since it accumulates all insertions over entire container).

Of course you cant reset the per-index stamps (or you lose the count), so the 'free' flags and such need to get their own variable (instead of being specific stamp values), or use a few bits of the stamp counter for those flags (if you do the latter, ensure those bits dont interfere with comparison, and that overflow doesnt corrupt the bits).

## Create an account

Register a new account

1. 1
Rutin
37
2. 2
3. 3
4. 4
5. 5

• 9
• 12
• 14
• 9
• 9
• ### Forum Statistics

• Total Topics
633348
• Total Posts
3011459
• ### Who's Online (See full list)

There are no registered users currently online

×