c++ - g++-5.1.1 仅在使用优化标志时警告未使用的变量

标签 c++ c++11 g++4.8 g++5.1

在一个大型项目中,我收到了一些来自 g++-5.1.1 的编译器警告 仅在构建发布版本(使用优化标志)时而不是 在构建调试版本时(禁用大多数编译器优化)。 我已经使用命令将问题缩小到下面列出的最小示例 重现问题。如果我使用 g++-4.8.4,则不会出现此问题。是 这是 g++-5.1.1 中的错误吗?或者,这段代码是否在做一些合法错误的事情并需要警告?为什么它不对代码中列出的最后三种情况产生任何警告(有关解释,请参阅底部的编辑)?

对于那些感兴趣的人,这里是bug report在 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 {} ;

编辑:正如 Ryan Haining 在评论中提到的,container_2container_3 将具有 extern 链接,编译器无法发出警告关于它们的用法。

最佳答案

如果我们查看 -Wunused-variable 的文档,这看起来像是一个错误它说(强调我的):

This option implies -Wunused-const-variable for C, but not for C++

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

Warn whenever a constant static variable is unused aside from its declaration. This warning is enabled by -Wunused-variable for C, but not for C++. In C++ this is normally not an error since const variables take the place of #defines in C++.

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

这个 gcc 错误报告:-Wunused-variable ignores unused const initialised variables也是相关的。尽管它是针对 C 的,但也讨论了 C++ 的情况。

关于c++ - g++-5.1.1 仅在使用优化标志时警告未使用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917767/

相关文章:

c++ - 定义类 X 的析构函数,它继承自指向对象 Y 的指针 vector 并具有指向 Z 的指针数组

floating-point - 负零的平方根

c++ - atof 随机无法正常工作

c++ - 非法调用非静态成员函数

c++ - Qt Qml错误: Unable to assign [undefined] to QString in a subclassed QAbstractItemModel for Qml TreeView

c++ - 为什么while循环不需要用户在c++中输入

c++ - 为什么 shared_ptr<A> 不隐式转换为 shared_ptr<A const>?

c++ - 这是组合 std::generate_n 和 std::back_inserter 的正确方法吗?

c++ - 从具有默认参数的类模板继承

c++ - 末端指针会与其他对象重叠吗?