I cannot find where the standard ensures that your proposed code will work. Firstly, I can’t find the part of the standard that supports what you quoted on CppReference.com, but even if we take this application on faith, it still only says that it can allocate additional space. If not, you are sunk.
The standard says about aligning the memory returned by operator new[] : "The returned pointer must be properly aligned so that it can be converted to a pointer to any complete object type ...". (C ++ 03, §3.7.2.1 / 2; C ++ 11, §3.7.4.1 / 2) However, in the context where you plan to allocate memory, the type that you plan to store in it is the full type. And besides, the result of operator new[] does not necessarily coincide with the result of the new expression new char[…] ; the latter is allowed to allocate additional space for its own accounting department of the array.
You can use C ++ 11 std::align . To ensure that you allocate space that can be aligned with the required amount, you will have to allocate object_size() + object_alignment() - 1 bytes, but in practice allocating only object_size() bytes is likely to be fine. So you can try using std::align something like this:
size_t buffer_size = object_size(); void* p = operator new(buffer_size); void* original_p = p; if (!std::align(object_alignment(), object_size(), p, buffer_size) {
The dispenser described in another question does the same. It has been configured for the type of the selected object, to which you do not have access, but this is not required. The only time it uses its template type argument is to evaluate the sizeof and alignof that you already have from your object_size and object_alignment .
This is similar to what is required from the consumers of your library. It would be much more convenient for them if you would move the selection behind the API:
void* object_construct() { return new internal_object(); }
Be sure to move the kill by calling delete , not just the destructor.
This leads to the fact that any alignment issues disappear, because the only module that really needs to know this is the one that already knows everything else about the selected type.
Rob Kennedy Oct 20 '14 at 17:51 2014-10-20 17:51
source share