ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-09-18 13:05:09  阅读:232  来源: 互联网

标签:reinterpret-cast placement-new strict-aliasing c language-lawyer


放置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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有