其他分享
首页 > 其他分享> > c – placement new的返回值与其操作数的转换值之间是否存在(语义)差异?

c – placement new的返回值与其操作数的转换值之间是否存在(语义)差异?

作者:互联网

放置new的返回值与其操作数的转换值之间是否存在(语义)差异?

struct Foo { ... };
char buffer[...];

Foo *a = new(buffer) Foo;
Foo *b = reinterpret_cast<Foo *>(buffer);

a和b在某种程度上有所不同吗?

编辑:根据DaBler的评论,这个问题告诉我们,如果使用const / reference成员则存在差异:Placement new and assignment of class with const member

所以,我的一点点更新问题:如果Foo没有const或引用成员,a和b是否有任何不同?

解决方法:

只有a可以安全地用于直接访问由放置new-expression创建的Foo对象(我们将其称为x以便于参考).使用b需要std :: launder.

a的值在[expr.new]/1中指定:

If the entity is a non-array object, the result of the new-expression
is a pointer to the object created.

因此,a的值是“指向x的指针”.当然,这个指针可以安全地用于访问x.

reinterpret_cast< Foo *>(缓冲区)将数组到指针的转换应用于缓冲区(参见[expr.reinterpret.cast]/1).应用转换后的结果值是“指向缓冲区的第一个元素的指针”.
这是指向不同类型的对象指针的对象指针的reinterpret_cast,并且在[expr.reinterpret.cast]/7被定义为等效于static_cast< Foo *>(static_cast< void *>(缓冲区)).

内部转换为void *实际上是一个隐式转换.每[conv.ptr]/2,

The pointer value is unchanged by this conversion.

因此内部转换产生void *,其值为“指向缓冲区的第一个元素的指针”.

外部演员由[expr.static.cast]/13管理,我已经轻轻地重新格式化为要点:

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.

  • If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T,
    then the resulting pointer value is unspecified.

  • Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification)
    that is pointer-interconvertible with a, the result is a pointer to
    b.

  • Otherwise, the pointer value is unchanged by the conversion.

假设缓冲区已经适当地对齐(如果不是这样,那么在此之前你会遇到麻烦),第一个子弹是不适用的.第二个子弹同样不适用,因为这里没有pointer-interconvertiblity.接下来我们点击第三个子弹 – “转换时指针值不变”并保持“指向缓冲区第一个元素的指针”.

因此,b不指向Foo对象x;它指向缓冲区的第一个char元素,即使它的类型是Foo *.因此它不能用于访问x;试图这样做会产生未定义的行为(对于非静态数据成员的情况,从[expr.ref]省略;对于非静态成员函数的情况,到[class.mfct.non-static]/2).

要从b恢复指向x的指针,可以使用std :: launder:

b = std::launder(b); // value of b is now "pointer to x"
                     // and can be used to access x

标签:reinterpret-cast,placement-new,strict-aliasing,c,language-lawyer
来源: https://codeday.me/bug/20190918/1811123.html