c – 使用 *** 作符删除从放置新的指针获得的合法性

c – 使用 *** 作符删除从放置新的指针获得的合法性,第1张

概述我很确定这段代码应该是非法的,因为它显然不会工作,但似乎被C 0x FCD允许. class X { /* ... */};void* raw = malloc(sizeof (X));X* p = new (raw) X(); // according to the standard, the RHS is a placement-new expression::operator dele 我很确定这段代码应该是非法的,因为它显然不会工作,但似乎被C 0x FCD允许.
class X { /* ... */};voID* raw = malloc(sizeof (X));X* p = new (raw) X(); // according to the standard,the RHS is a placement-new Expression::operator delete(p); // definitely wrong,per litb's answerdelete p; // legal?  I hope not

也许你们中的一位语言律师可以解释这个标准是禁止这个.

还有一个数组形式:

class X { /* ... */};voID* raw = malloc(sizeof (X));X* p = new (raw) X[1]; // according to the standard,the RHS is a placement-new Expression::operator delete[](p); // definitely wrong,per litb's answerdelete [] p; // legal?  I hope not

This is the closest question我能找到.

编辑:我只是不认为标准的语言限制参数的函数voID :: operator delete(voID *)的用法以任何有意义的方式应用于delete-Expression中的delete *** 作数.最好,两者之间的连接是非常脆弱的,并且允许一些表达式作为删除的 *** 作数,这些 *** 作不能传递给voID :: operator delete(voID *).例如:

struct A{  virtual ~A() {}};struct B1 : virtual A {};struct B2 : virtual A {};struct B3 : virtual A {};struct D : virtual B1,virtual B2,virtual B3 {};struct E : virtual B3,virtual D {};int main( voID ){  B3* p = new E();  voID* raw = malloc(sizeof (D));  B3* p2 = new (raw) D();  ::operator delete(p); // definitely UB  delete p; // definitely legal  ::operator delete(p2); // definitely UB  delete p2; // ???  return 0;}

我希望这可以说明一个指针是否可以被传递给voID operator delete(voID *)与该指针是否可以用作delete的 *** 作数无关.

解决方法 [basic.stc.dynamic.deallocation] p3的标准规则

Otherwise,the value supplIEd to operator delete(voID*) in the standard library shall be one of the values returned by a prevIoUs invocation of either operator new(size_t) or operator new(size_t,const std::nothrow_t&) in the standard library,and the value supplIEd to operator delete[](voID*) in the standard library shall be one of the values returned by a prevIoUs invocation of either operator new[](size_t) or operator new[](size_t,const std::nothrow_t&) in the standard library.

您的删除呼叫将调用库的运算符delete(voID *),除非您已经覆盖.既然你没有说过什么,我会假设你没有.

上面的“应该”应该是像“行为不定义,如果不是”,所以它不被误认为是一个可诊断的规则,它不是由[lib.res.on.arguments] p1.这被n3225纠正了,所以不能再错了.

总结

以上是内存溢出为你收集整理的c – 使用 *** 作符删除从放置新的指针获得的合法性全部内容,希望文章能够帮你解决c – 使用 *** 作符删除从放置新的指针获得的合法性所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1252073.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存