最近看到一段代码,如下:
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<void*>(&_S_empty_rep_storage);
return *reinterpret_cast<_Rep*>(__p);
}
这里为何要先转换为void*, 为什么不直接转换为_Rep* ?
天蓬老师2017-04-17 13:18:32
Isn’t the above comment written to avoid strict-aliasing warnings?
As for why you should avoid warnings, Werror will treat all warnings as errors
You can read these two articles about this warning
http://cellperformance.beyond3d.com/articles/2006/06/ understanding-strict-aliasing.html
http://blog.csdn.net/dbzhang800/article/details/6720141
怪我咯2017-04-17 13:18:32
If you convert it directly to _Rep*, the compiler will give a warning (strict-aliasing Warning) after enabling certain restriction levels. The author wants the compiler to shut up, so he uses a "hack", first convert into void* and then into _Rep*, and the compiler will not give a warning for these two separate steps.
In practice, this is done to avoid some code checking restrictions, which will not bring actual benefits. Instead, it may introduce potential bugs by ignoring compiler warnings.