这个问题源于对我的回答的思考给定两个不同类型的对象及其在内存中的相对位置,我可以从指向另一个对象的指针派生出指向另一个对象的指针吗? https://stackoverflow.com/questions/76113351/given-two-objects-of-different-types-and-their-relative-location-in-memory-can.
我的假设是当前标准允许,假设sizeof(int) == sizeof(float)
, alignof(int) == alignof(float)
and sizeof(int) == alignof(int)
, 优化函数g
in
void f(float*);
int g() {
alignas(int) std::byte storage[sizeof(int)*2];
auto x = new(storage) float();
auto y = new(storage + sizeof(float)) int();
f(x);
return *y;
}
总是回来0
,因为不可能达到int
对象从float
对象由于可达性先决条件std::launder
。据我所知,当前的编译器实际上没有这样做。
然而,假设f
定义如下:
struct A {
float x;
int y;
};
void f(float* x) {
reinterpret_cast<A*>(x)->y = 1;
}
假设sizeof(A) == 2*sizeof(int)
and alignof(A) == alignof(int)
关于实施。
Doesn't f
然后有明确定义的行为,因此优化是不可能的,因为隐式对象创建时的生命周期storage
开始可以创建一个A
其中的对象int
and float
对象将成为成员子对象,并且float
对象是可以与指针相互转换的A
object?
我是否误解了预期的优化好处std::launder
可达性先决条件还是 C++20 的隐式对象创建只是搞砸了?它是否应该仅适用于非标准布局类型?
另请参阅我的相关问题std::launder 与放置 - 新的可达性条件 https://stackoverflow.com/questions/70807452/stdlaunder-vs-placement-new-reachabibility-condition.