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

浏览:32日期:2023-05-23

问题描述

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

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

问题解答

回答1:

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

回答2:

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

相关文章: