8

大規模なプロジェクトで、リリース バージョン (最適化フラグを使用) をビルドするときのみ g++-5.1.1 からコンパイラ警告が表示されますが、デバッグ バージョン (ほとんどのコンパイラ最適化を無効にする) をビルドするときは表示されません。問題を再現するコマンドを使用して、以下にリストされている最小限の例に問題を絞り込みました。g++-4.8.4 を使用すると問題は発生しません。これは g++-5.1.1 のバグですか? それとも、このコードは正当に間違ったことを行っており、その警告を正当化していますか? コードにリストされている最後の 3 つのケースで警告が生成されないのはなぜですか (説明については、下部の編集を参照してください)。

興味のある方は、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_2リンケージcontainer_3externあり、コンパイラはそれらの使用について警告する方法がありません。

4

1 に答える 1

1

-Wunused-variableのドキュメントを見ると、これはバグのように見えます(私の強調):

このオプションは、C の場合は -Wunused-const-variable を意味しますが、C++ の場合は意味しません

そして、それを見ると、次のように書かれ-Wunused-const-variableています:

定数静的変数がその宣言を除いて使用されていない場合は常に警告します。この警告は、C では -Wunused-variable によって有効になりますが、C++ では有効になりません。C++ では、const 変数が C++ の #defines の代わりになるため、これは通常エラーではありません。

そして、この警告がgcc の最新リビジョンで消えることがわかります。

この gcc バグ レポート: -Wunused-variable ignores unused const initialized variablesも関連しています。これは C に反しますが、C++ のケースも議論されています。

于 2015-10-03T02:23:06.747 に答える