cra*_*ulf 8 c++ c++11 g++4.8 g++5.1
在一个大项目中,我只是在构建发布版本(使用优化标志)时才从g ++ - 5.1.1获得一些编译器警告,但是在构建调试版本时(这会禁用大多数编译器优化).我已经将问题缩小到下面列出的最小示例,其中包含重现问题的命令.如果我使用g ++ - 4.8.4,则不会出现此问题.这是g ++ - 5.1.1中的错误吗?或者,这段代码是否做了合法错误的事情并保证警告?为什么不对代码中列出的最后三种情况产生任何警告(请参阅底部的编辑以获得一些解释)?
对于那些感兴趣的人,这是GCC的Bugzilla中的错误报告.
/*
This code complains that the variable 'container' is unused only if optimization
flag is used with g++-5.1.1 while g++-4.8.4 does not produce any warnings in
either case. Here are the commands to try it out:
$ g++ --version
g++ (GCC) 5.1.1 20150618 (Red Hat 5.1.1-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ -c -std=c++11 -Wall -g -O0 test_warnings.cpp
$ g++ -c -std=c++11 -Wall -O3 test_warnings.cpp
test_warnings.cpp:34:27: warning: ‘container’ defined but not used [-Wunused-variable]
const std::array<Item, 5> container {} ;
^
*/
#include <array>
struct Item
{
int itemValue_ {0} ;
Item() {} ;
} ;
//
// The warning will go away if you do any one of the following:
//
// - Comment out the constructor for Item.
// - Remove 'const' from the next line (i.e. make container non-const).
// - Remove '{}' from the next line (i.e. remove initializer list).
//
const std::array<Item, 5> container {} ;
//
// These lines do not produce any warnings:
//
const std::array<Item, 5> container_1 ;
std::array<Item, 5> container_2 ;
std::array<Item, 5> container_3 {} ;
Run Code Online (Sandbox Code Playgroud)
编辑:正如Ryan Haining在评论中提到的那样,container_2并且container_3会有extern链接,编译器也无法警告它们的用法.
这看起来像是一个错误,如果我们查看-Wunused-variable的文档,它会说(重点是我的):
此选项对于 C 意味着 -Wunused-const-variable,但对于 C++ 则不然
如果我们看一下-Wunused-const-variable它说:
每当常量静态变量除了其声明之外未使用时发出警告。此警告由 C 的 -Wunused-variable 启用,但不适用于 C++。在 C++ 中,这通常不是错误,因为 const 变量取代了 C++ 中的#defines。
我们可以看到这个警告在gcc 的 head 修订版中消失了。
这个 gcc 错误报告:-Wunused-variable 忽略未使用的 const 初始化变量也是相关的。尽管它是针对 C 的,但也讨论了 C++ 的情况。