Do we need to use std::launder when doing pointer arithmetic within a standard-layout object (e.g., with offsetof)?

纵然是瞬间 提交于 2019-12-02 18:58:13

You question was:

Do we need to use std::launder when doing pointer arithmetic within a standard-layout object (e.g., with offsetof)?

No.

Using only a standard layout type cannot result in a situation where you would ever need to use std::launder.

The example can be simplified a bit: just use an integer type to hold the address instead of the unsigned char*.

Using uintptr_t instead:

struct Foo {
    float x, y, z;
};

static_assert(std::is_standard_layout<Foo>::value);

Foo f;

uintptr_t addr = reinterpret_cast<uintptr_t>(&f) + offsetof(Foo, z);//OK: storing addr as integer type instead
//uintptr_t addr = reinterpret_cast<uintptr_t>(&f.z);//equivalent: ei. guarenteed to yield same address!

*reinterpret_cast<float*>(addr) = 42.0f;

The example is extremely simpel now - there is no longer a conversion to unsigned char* and we are just getting an adddress and casting back to original pointer type.. (do you also imply this is broken ?)

std::launder is usually just needed in a subset of cases (eg. due to a const member) where you change (or create) an underlying object in some runtime manner (eg. via placement new). Mnemonic: the object is 'dirty' and needs to be std::launder'ed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!