简体   繁体   中英

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

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.

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* . Only that variables of type char* and Fred* may point to the same object, and be used to access it.

Quoting [basic.lval] paragraph 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:

  • the dynamic type of the object,

    [..]

  • a char or unsigned char type.

Placement-new creates a new object. 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.

Before placement-new, there is storage filled with char objects. After placement-new, there is storage filled with one Fred object.

Since there is no aliasing, there are no strict-aliasing problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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