简体   繁体   English

严格的混叠规则违反

[英]Strict aliasing rule violation

In this link from the isocpp.org faq in the example provided, a Fred object is being constructed with placement new to a buffer that is being allocated for another object ie for 在提供的示例中来自isocpp.org常见问题的链接中,正在构造Fred对象,并将其放置在新的缓冲区中,该缓冲区正分配给另一个对象,即为

char memory[sizeof(Fred)]

As I know the strict aliasing rules allows us to do the opposite ie for an object of whatever type, we are allowed to have a char* point at it and we can dereference that pointer and use it as we want. 众所周知,严格的别名规则使我们可以做相反的操作,即对于任何类型的对象,都可以在其上使用char*点,并且可以取消引用该指针并根据需要使用它。

But here in the example the opposite is happening. 但是在此示例中,情况正相反。 What am I missing? 我想念什么?

The strict aliasing rules doesn't mention that Fred* must be cast to char* . 严格的别名规则没有提及必须将Fred*强制转换为char* Only that variables of type char* and Fred* may point to the same object, and be used to access it. 只有char*Fred*类型的变量可以指向同一对象,并可以用来访问它。

Quoting [basic.lval] paragraph 8 引用[basic.lval]第8段

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: 如果程序尝试通过以下类型之一以外的glvalue访问对象的存储值,则行为未定义:

  • the dynamic type of the object, 对象的动态类型,

    [..] [..]

  • a char or unsigned char type. 字符或无符号字符类型。

Placement-new creates a new object. 新的Placement创建一个新对象。 It doesn't alias the old object. 它不会为旧对象起别名。 The old object (the char array in this example) is considered to stop existing when the placement-new executes. 执行placement-new时,旧对象(此示例中为char数组)被认为已停止存在。

Before placement-new, there is storage filled with char objects. 在进行新的放置之前,存储已充满char对象。 After placement-new, there is storage filled with one Fred object. 新放置后,将有一个Fred对象填充存储空间。

Since there is no aliasing, there are no strict-aliasing problems. 由于没有别名,因此没有严格的别名问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM