和安置新普通删除

和安置新普通删除

本文介绍了混合运营商新的[]和安置新普通删除[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是出于好奇,是下列法律?

  X * P =的static_cast< X * GT;(运营商新的[](3 * sizeof的(X)));
新的(p + 0)×();
新的(p + 1)×();
新的(p + 2)×();删除[]芘; //我可以在使用delete [这里]?或者是未定义的行为?

同样的:

  X * Q =新的X [3]();(Q + 2) - >〜X();
(Q + 1) - >〜X();
(Q + 0) - >〜X();
运营商删除[](Q);


解决方案

我是pretty确保两个给UB。

§5.3.4/ 12表示一个新的前pression的数组形式可能会增加开销的一些任意金额分配的内存量。该阵列可以删除/然后可以用它做预计将有额外的内存的东西,但不是因为你没有分配,预计的额外空间。至少,它通常会为额外的内存,预计量至少补偿分配给回到它认为从返回地址运营商新的 - 但因为你还没有分配额外的内存或应用的偏移,当它到它会传递一个指向的operator delete [] 不是从<$返回C $ C>运营商新的[] ,导致UB(,事实上,即使是在试图返回地址开始之前形成的地址在技术上UB)。

同样的部分说,如果它分配额外的内存,它通过架空的量来抵消返回的指针。当/如果你调用的operator delete [] 与从全新的前pression返回不补偿偏移指针,你调用的operator delete [] 的指针这是从一个运营商新的[] 返回不同,给人UB一次。

§5.3.4/ 12是一个非规范性的音符,但我没有看到任何在规范文本反驳它。

Just out of curiosity, is the following legal?

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

delete[] p;   // Am I allowed to use delete[] here? Or is it undefined behavior?

Similarly:

X* q = new X[3]();

(q + 2)->~X();
(q + 1)->~X();
(q + 0)->~X();
operator delete[](q);
解决方案

I'm pretty sure both give UB.

§5.3.4/12 says the array form of a new expression may add some arbitrary amount of overhead to the amount of memory allocated. The array delete can/could then do something with the extra memory it expects to be there, but isn't since you didn't allocate the extra space it expects. At the very least it's normally going to at least compensate for the amount of extra memory it expected to be allocated to get back to the address it believes was returned from operator new -- but since you haven't allocated extra memory or applied an offset, when it does to it'll pass a pointer to operator delete[] that wasn't returned from operator new[], leading to UB (and, in fact, even attempting to form the address before the beginning of the returned address is technically UB).

The same section says that if it allocates extra memory, it has to offset the returned pointer by the amount of that overhead. When/if you call operator delete[] with the pointer that was returned from the new expression without compensating for the offset, you're calling operator delete[] with a pointer that's different from the one operator new[] returned, giving UB again.

§5.3.4/12 is a non-normative note, but I don't see anything in the normative text to contradict it.

这篇关于混合运营商新的[]和安置新普通删除[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:40