Lessi
Lessi

Reputation: 175

c++ how to properly call deallocate within custom container

I created a custom container class that looks like this:

template <typename T, typename Alloc=std::allocator<T>>
class container {
    ...
};

To allocate memory i use std::allocator_traits<Alloc>::allocate(some_size).
I guess I could also just use Alloc::allocate(some_size).
The problem comes when I want to deallocate the memory with std::allocator_traits<Alloc>::deallocate(...) or Alloc::deallocate(...), because deallocate called with std::allocator_traits is not static and requires an allocator object to be passed.
Alloc::deallocate would work because its static.
Whats the difference between those two types of calling the functions of an allocator and why is std::alloctor_traits<Alloc>::deallocate(...) not static anymore?

A little bit of my real code:

template <typename T, typename Alloc>
ring<T, Alloc>::~ring() {
    if (__n_items > 0) {
        for(reference item : *this) {
            item.~value_type();
        }
        std::allocator_traits<Alloc>::deallocate(__buffer, __size);
    }
}

Throwing too few arguments cause of the missing allocator instance.

Upvotes: 1

Views: 176

Answers (1)

Sneftel
Sneftel

Reputation: 41454

Both the allocate and deallocate methods of allocator_traits require an allocator object. Standard library containers are given an allocator instance to store and use (ordinarily users rely on the default constructor behavior, which default-constructs such an allocator). If you expect to use your container class with a stateful allocator, you should do the same; if your custom allocator has no per-instance state, you can just default-construct one as needed.

Upvotes: 3

Related Questions