Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::allocator construct/destroy vs. placement new/p->~T()

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.

like image 534
Evan Teran Avatar asked Mar 17 '09 01:03

Evan Teran


2 Answers

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

like image 190
jalf Avatar answered Nov 04 '22 21:11

jalf


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.

like image 42
Vinay Avatar answered Nov 04 '22 21:11

Vinay