2015-10-03 39 views
8

在一个大的项目,我已经得到了一些编译器警告从G ++而不是构建调试版本(禁用大多数编译器优化)时的 。 我已经将问题缩小到下面列出的最小范例,并使用命令 来重现问题。如果我使用g ++ - 4.8.4,则不会发生此问题。是 这是g ++ - 5.1.1中的一个bug吗?或者,这段代码是否做了一些合理错误的事情并保证警告?为什么它不会为代码中列出的最后三种情况产生任何警告(请参阅底部的编辑以获取一些解释)?克++ - 建筑的发行版(使用优化标志)只有当5.1.1 - 5.1.1警告有关未使用的变量,只有当优化标志用于

对于那些谁有兴趣,这里是在GCC的Bugzilla的bug report

/* 

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 {} ; 

编辑:正如在评论中提到的由Ryan海宁,container_2container_3将有extern联动和编译器没有警告他们使用的方式。

+2

'container_2'和'container_3'将有隐含的'extern'联动,所以无法知道他们是否使用 –

+0

@RyanHaining,好点的那两个。我会让他们完成所有四种组合(带/不带'const'和'{}')。 – crayzeewulf

回答

1

这看起来像一个错误,如果我们看一下文档-Wunused-variable它说(重点煤矿):

这种选择意味着-Wunused const的变量为C,但不能用于C++

,如果我们看一下-Wunused-const-variable它说:

只要有一个常量静态变量未被使用,就会发出警告,即 声明。此警告由C的-Wunused-variable启用,但 不适用于C++。 在C++中,这通常不是错误,因为const 变量取代了C++中的#defines。

我们可以看到这个警告在the head revision of gcc消失。

这GCC bug报告:-Wunused-variable ignores unused const initialised variables也有关。虽然它是针对C的C++案件也进行了讨论。

+0

感谢所有这些有用的信息。看起来像使用不同版本的gcc的警告触发器。所以它确实看起来像一个错误。 – crayzeewulf