Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::list want to call my allocator with no arguments?

Sorry, I can not paste the specific code.
I hope this small sample is enough:

Let's say I have an allocator like this:

template <class T>
class MyAllocator
{
// ... typedefs

    MyAllocObject _allocObject;

public:
    MyAllocator() {
    // _allocObject = new ..
    }

    MyAllocator(const MyAllocator& alloc) {
        _allocObject = alloc.getAllocObject();
    }

    template <class U>
    MyAllocator(const MyAllocator<U>& alloc) {
        _allocObject = alloc.getAllocObject();
    }

    MyAllocator(const MyAllocObject& allocObject) {
        _allocObject = allocObject;
    }

    inline pointer allocate(size_type size) {
        return _allocObject->alloc(size);
    }

// other functions
};

And is used like this:

MyAllocObject object;
MyAllocator<int> myAlloc(object);
std::list<int, MyAllocator<int> > list(myAlloc);

I experienced, that if the default constructor is missing, the code does not compile, so I added it.
But the problem is, that I depend on that argument, because that is what I use for my custom memory allocations.

What can I do in this case?

like image 822
otisonoza Avatar asked Oct 30 '22 16:10

otisonoza


1 Answers

Before C++11, STL implementations were allowed to require allocators to behave as-if stateless.

"behave as-if stateless" means STL could rely on the following to work:

MyAllocator a1;
void * p = a1.allocate(77, 0);

MyAllocator a2;
a2.free(p);

(IIRC this simplifies implementation of some container operations.)

"were allowed to require" means STL implementation could support stateful allocators (like yours), but didn't have to.


C++ 11 requires support for stateful allocators.
I couldn't, however, find a quick introduction to that (anyone wants to add that?) This thread might give you some leads.


If you are bound to a particular compiler that does not support stateful allocators, you have a few not-so-shiny options:

  • include a reference to your state as template argument of the allocator
  • in your allocation, include a back-link to the allocator in question (usually destroys the purpose of a custom allocator for small data)
like image 85
peterchen Avatar answered Nov 08 '22 08:11

peterchen