Maison  >  Questions et réponses  >  le corps du texte

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_lee2715 Il y a quelques jours687

répondre à tous(2)je répondrai

  • 天蓬老师

    天蓬老师2017-04-17 13:18:32

    上面注释不是写了么,避免strict-aliasing警告。
    至于为什么要避免警告呢,Werror会把所有警告视为错误
    关于这个警告可以看一下这两篇文章
    http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html
    http://blog.csdn.net/dbzhang800/article/details/6720141

    répondre
    0
  • 怪我咯

    怪我咯2017-04-17 13:18:32

    如果直接转成_Rep*,编译器在启用某些限制级别后会给出警告(strict-aliasing Warning),而作者想让编译器闭嘴,就用了一个"hack",先转成void*再转成_Rep*,而这分别的两步编译器不会给出警告。
    实际中这么做是为了避开一些代码检查限制,并不会带来实际上的好处,反而可能因为忽视编译器的警告而引入潜在的bug。

    répondre
    0
  • Annulerrépondre