最近看到一段代码,如下:
static size_type _S_empty_rep_storage[];
static _Rep& _S_empty_rep() _GLIBCXX_NOEXCEPT
{
// NB: Mild hack to avoid strict-aliasing warnings. Note that
// _S_empty_rep_storage is never modified and the punning should
// be reasonably safe in this case.
void* __p = reinterpret_cast(&_S_empty_rep_storage);
return *reinterpret_cast<_Rep*>(__p);
}
这里为何要先转换为void*, 为什么不直接转换为_Rep* ?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果直接转成_Rep*,编译器在启用某些限制级别后会给出警告(strict-aliasing Warning),而作者想让编译器闭嘴,就用了一个"hack",先转成void*再转成_Rep*,而这分别的两步编译器不会给出警告。
实际中这么做是为了避开一些代码检查限制,并不会带来实际上的好处,反而可能因为忽视编译器的警告而引入潜在的bug。