Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the intent behind C++ Standard requirement that new char[] yields aligned memory?

According to C++03 Standard, 5.3.4/10

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 most stringent alignment requirement (3.9) of any object type whose size is no greater than the size of the array being created.

The allocation function (operator new[]()) is also required to allocate memory aligned for any possible type. So the quoted part effectively says that new char[sizeof(T)] should yield memory properly aligned for type T.

What's the purpose of this requirement? I could just call operator new() (or operator new[]()) which is guaranteed to return properly aligned memory and have the propery aligned memory. I mean anyway new char[] will call operator new()[] so I could just call it myself.

What's the purpose of the quoted requirement? Why not just call operator new[]() directly?

like image 466
sharptooth Avatar asked Oct 22 '22 10:10

sharptooth


1 Answers

I generally just call operator new directly, but the authors of the standard decided to also allow using new char[] as a means of acquiring raw memory. Thus the alignment requirement.

like image 148
James Kanze Avatar answered Nov 15 '22 07:11

James Kanze