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

前端之家收集整理的这篇文章主要介绍了c – 使用操作符删除从放置新的指针获得的合法性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很确定这段代码应该是非法的,因为它显然不会工作,但似乎被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 answer
delete 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 answer
delete [] 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++相关文章