int main(){
auto* ptr = (int*) ::operator new(sizeof(int)*10, std::align_val_t(alignof(int))); //#1
ptr[1] = 4; //#a
}
Consider the above code, what the standard says are listed in the following:
- The pointer returned shall be suitably aligned so that it can be converted to a pointer to any suitable complete object type ([new.delete.single]) and then used to access the object or array in the storage allocated
- If the allocated type is a non-array type, the allocation function's name is operator new and the deallocation function's name is operator delete. If the allocated type is an array type, the allocation function's name is operator new[] and the deallocation function's name is operator delete[].
- If the entity is a non-array object, the new-expression returns a pointer to the object created. If it is an array, the new-expression returns a pointer to the initial element of the array
And the rules about pointer arithmatic says:
expr.add#4
- If the expression P points to element x[i] of an array object x with n elements,86 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i+j] if 0≤ i+j ≤ n; otherwise, the behavior is undefined.
So, I wonder Is it an undefined behavior when use the pointer at #a? I think it violate the bullet 4. In addition, at the look of implementation of std::allocate of MSVC. It seems to use operator new() to allocate the space and use the return pointer as a pointer to element of array.
It seems to the standard does not say what the return pointer point to what original object when directly invoke ::operator new(...). It only says the return pointer that resulted from invoking such allocate function can be converted to a pointer to an object which has suitably aligned.
UPDATE:
what I concerned is dynamic-construction-of-arrays
The most implementation of std::vector use the std::allocate and std::vector has a non-static data member record the result from std::allocate. When use the object of std::vector as arr[i], the implementation will use the non-static data member as the pointer to element of array type to access arr[i]. I think it should be UB? I.E, we are permitted to use the pointer that return from allocation function as the operand of new-placement to construct an object, However If we use the pointer to access ith object or any iterator to access ith object, It means it's UB?