views:

877

answers:

2

For a project of mine, I am writing some STL containers from scratch (I have my reasons). Since I am mimicking the functionality and interfaces of the STL so closely I am doing my best to keep with the policy "if it has the same name as a standard construct, it will conform to the standard as much as possible."

So, of course my containers take allocators as a template parameter, which is very nice as it allows for some custom allocation schemes. On to my question.

The std::allocator interface separates memory allocation from object construction. Likewise it separates deallocation from destruction. This makes sense since where you get memory from is more or less irrelevant to properly constructing an object in c++.

So there are two construction/deallocation functions which look like this for the default implementation (lifted straight from a book):

void construct(pointer p, const T& val)    { new(p) T(val); }
void destroy(pointer p)                    { p->~T(); }

as you can see construct simply calls placement new and destroy simply calls the destructor.

Is there any reason to use these over just using placement new and destructor syntax? can a "correct" allocator implement these in another way? Or am I guaranteed that all allocator implementations which conform to the standard will have there construct/destroy methods implemented in this way?

More to the point, is it safe to say that I can always use the std::uninitialized_copy and std::uninitialized_fill for constructing the elements of my containers?

Thanks.

+3  A: 

This is just to hide the details of allocation in a method. i.e., we are providing the APIs for construction and destruction, in the future we can change the implementation. Now we are using placement new to allocate the memory, in the future if we want to change the allocation we just have to change these two methods.

Vinay
yea, I can agree with that. But I am curious if the standard allows them to be changed? (especially with custom allocators which we don't have to wait for a new std for...).
Evan Teran
+7  A: 

The allocator could add logging statements before and after construction/destruction, or any other side effects it cared to do.

Of course the actual construction has to occur by calling placement new and the destructor, but it doesn't say in the rulebook that nothing else must happen in the construct/destroy functions

jalf
yes, that's a good point, it could be a good hook for "post-allocation/pre-construction" logging or memleak tracking.
Evan Teran