Mixing operator new[] and placement new with ordinary delete[]

前端 未结 5 2078
悲&欢浪女
悲&欢浪女 2020-12-18 20:10

Just out of curiosity, is the following legal?

X* p = static_cast(operator new[](3 * sizeof(X)));
new(p + 0) X();
new(p + 1) X();
new(p + 2) X();

         


        
5条回答
  •  北海茫月
    2020-12-18 20:36

    If they aren't UB, they should be. In example 1 you are using delete[] where the underlying mechanism has no clue of how many objects are to be destructed. If the implementation of new[] and delete[] uses cookies, this will fail. The code in example 2 assumes that the address q is the correct address to pass to operator delete[], and this is not the case in an implementation that uses cookies.

提交回复
热议问题