std::清洗和严格的混叠规则

std::launder and strict aliasing rule

本文关键字:规则 清洗 std      更新时间:2023-10-16

请考虑以下代码:

void f(char * ptr)
{
auto int_ptr = reinterpret_cast<int*>(ptr); // <---- line of interest 
// use int_ptr ... 
}
void example_1()
{
int i = 10;    
f(reinterpret_cast<char*>(&i));
}
void example_2()
{
alignas(alignof(int)) char storage[sizeof(int)];
new (&storage) int;
f(storage);
}

来自example_1电话的兴趣线:

Q1:在调用端,char指针正在为整数指针设置别名。这是有效的。但是,将其投射回int是否也有效?我们知道int在其生命周期内,但请考虑该函数是在另一个翻译单元中定义的(未启用链接时间优化(,并且上下文未知。然后编译器看到的只是:一个int指针想要为一个char指针设置别名,这违反了严格的别名规则。那么允许吗?

Q2:考虑到这是不允许的。我们在 17 C++获得了std::launder。它是一种指针优化屏障,主要用于访问一个对象,该对象被new放置在其他类型的对象的存储中,或者当涉及const成员时。我们可以使用它来给编译器一个提示并防止未定义的行为吗?

来自example_2电话的兴趣线:

Q3:这里应该需要std::launder,因为这是 Q2 中描述std::launder用例,对吧?

auto int_ptr = std::launder(reinterpret_cast<int*>(ptr));

但再次考虑f在另一个翻译单元中定义。编译器如何知道我们的放置new,这发生在调用端?编译器(只看到函数f(如何区分example_1example_2?或者以上所有只是假设,因为严格的混叠规则只会排除所有内容(记住,char*int*不允许(,编译器可以做它想做的事?

后续问题:

Q4:如果上述所有代码由于混叠规则而出错,请考虑将函数f更改为采用 void 指针:

void f(void* ptr)
{
auto int_ptr = reinterpret_cast<int*>(ptr); 
// use int_ptr ... 
}

然后我们没有混叠问题,但仍然存在std::launder的情况example_2.我们是否更改了调用方并将我们的example_2函数重写为:

void example_2()
{
alignas(alignof(int)) char storage[sizeof(int)];
new (&storage) int;
f(std::launder(storage));
}

还是功能fstd::launder就足够了?

严格的混叠规则是对实际用于访问对象的 glvalue 类型的限制。对于该规则而言,所有重要的是 a( 对象的实际类型,以及 b( 用于访问的 glvalue 的类型。

指针经过的中间强制转换是无关紧要的,只要它们保留指针值即可。(这是双向的;再多聪明的强制转换或洗钱也无法治愈严格的混叠违规。

只要ptr实际指向类型int的对象,f就是有效的,假设它通过int_ptr访问该对象而不进行进一步的强制转换。

example_1在写入时有效;reinterpret_cast不会更改指针值。

example_2是无效的,因为它f提供了一个指针,该指针实际上并不指向int对象(它指向storage数组的生命周期外第一个元素(。请参阅放置 new 的返回值与其操作数的强制转换值之间是否存在(语义(差异?

你不需要在函数 f(( 中 std::launder。作为尽可能通用的函数 f(( 可以与任何指针一起使用:脏(需要洗衣服(或不脏。它仅在呼叫端知道,因此您必须使用如下所示的内容:

void example_2()
{
alignas(alignof(int)) char storage[sizeof(int)];
new (&storage) int;        // char[] has gone, now int there
f(std::launder(reinterpret_cast<int*>(storage)));  // assiming f(void* p)
}

而 f(( 本身是另一回事。正如你提到的,假设 f(( 被放置在一个共享库中,所以根本没有任何上下文假设。