With regard to alignment, there is something I don't understand about the difference between an explicit call to T* t = (T*) ::operator new(sizeof(T))
and T* t = (T*)new char[sizeof(T)]
, where T
is a C-like struct.
In the book "C++ Solutions Companion to The C++ Programming Language, Third Edition" (see exercise 12.9), the author says: "Note that one should not use the expression new char[n] to allocate raw memory because that memory may not satisfy the alignment requirements of a T, while an explicit call of the global operator new is guaranteed to yield storage that is sufficiently aligned for any C++ object.". This is also stated in an article I read on internet: http://www.scs.stanford.edu/~dm/home/papers/c++-new.html (see the "delete vs. delete[] and free" paragraph).
On the other hand, in my previous post Data alignment in C++, standard and portability a guy quoted the standard, plus a note at the end of the quote which contradicts the above people:
"A new-expression passes the amount of space requested to the allocation function as the first argument of type std::size_t. That argument shall be no less than the size of the object being created; it may be greater than the size of the object being created only if the object is an array. For arrays of char and unsigned char, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the strictest fundamental alignment requirement (3.11) of any object type whose size is no greater than the size of the array being created. [ Note: Because allocation functions are assumed to return pointers to storage that is appropriately aligned for objects of any type with fundamental alignment, this constraint on array allocation overhead permits the common idiom of allocating character arrays into which objects of other types will later be placed. — end note ]"
I am confused. Could you please tell me who is right here according to the standard and, in case, why is ::operator new()
different from new char[]
?