Home  >  Q&A  >  body text

c++ - 如何理解reinterpret_cast<void*>的用法?

最近看到一段代码,如下:

 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* ?

ringa_leeringa_lee2765 days ago706

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师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

    reply
    0
  • 怪我咯

    怪我咯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.

    reply
    0
  • Cancelreply