Search code examples
c++11stlnew-operatorallocator

Synonym function call for ::new((void*)p)T(value);


I am trying to write my own Allocator which can be used in STL. That far I could almost successfully finish but with one function I have my problem:

The Allocator used in STL should provide the function construct [example from a standard allocator using new & delete]:

// initialize elements of allocated storage p with value value
void construct (T* p, const T& value)
{
    ::new((void*)p)T(value);
}

I am stuck how to rewrite this using my own function which replaces the new keyword initializing it with the value.

This function construct is for example used in this code: fileLines.push_back( fileLine );

where

MyVector<MyString>      fileLines;
MyString                fileLine;

These are my typedefs where I use my own Allocator:

template <typename T> using MyVector = std::vector<T, Allocator<T>>;
using MyString = std::basic_string<char, std::char_traits<char>, Allocator<char>>;

I am confused because here is allocated a pointer to T which can be for example [when I understood it correctly] MySstring.

Do I understand it correctly that the pointer - allocated by new - will have 10 bytes, when value is 123456789 and then the provided value is copied to the new pointer?

My question:

How to rewrite the one line of code using my own function? For me the difficult point is how to get the length of value [which can have any type] in order I can correctly determinate the length of the allocated block and how to copy it in order it works for all possible types T?


Solution

  • The new operator in the construct function does not allocate anything at all, it's a placement new call, which takes an already allocated chunk of memory (which needs to have been previously allocated some way, and at least as large as sizeof(T)) and initializes it as a T object by calling the constructor of T, pretending that the memory pointed to by p is a T object.