Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::allocator in my own container class

Tags:

I am trying to write a container class which uses STL allocators. What I currently do is to have a private member

std::allocator<T> alloc_;

(this will later be templated so that the user can pick a different allocator) and then call

T* ptr = alloc_.allocate(1,0);

to get a pointer to a newly allocated 'T' object (and used alloc_.construct to call the constructor; see the answer below). This works with the GNU C++ library.

However, with STLPort on Solaris, this fails to do the right thing and leads to all sorts of bizarre memory corruption errors. If I instead do

std::allocator_interface<std::allocator<T> > alloc_;

then it is all working as it should.

What is the correct way to use the stl::allocator? The STLPort/Solaris version fails to compile with g++, but is g++ right?

like image 998
Kasper Peeters Avatar asked Mar 24 '10 16:03

Kasper Peeters


People also ask

What is custom allocator?

A custom allocator is a reasonable way to securely erase memory before it is deallocated.

What is std :: allocator?

std::allocator is used when you want to separate allocation and do construction in two steps. It is also used when separate destruction and deallocation is done in two steps. All the STL containers in C++ have a type parameter Allocator that is by default std::allocator.

What is a stack allocator?

Note: A stack-like allocator means that the allocator acts like a data structure following the last-in, first-out (LIFO) principle. This has nothing to do with the stack or the stack frame. The stack allocator is the natural evolution from the arena allocator.


1 Answers

You need to both allocate and construct with the allocator. Something like this:

T* ptr = alloc_.allocate(1,0);
alloc_.construct(ptr, value);

Lots of things are downright broken if you don't start with a properly constructed object. Imagine a std::string being allocated but not constructed. When you try to assign to it, it will first try to cleanup its old contents by freeing some data, which will of course be garbage values from the heap and crash.

like image 83
Evan Teran Avatar answered Dec 01 '22 12:12

Evan Teran