ソースファイルのローカル変数として連想配列の定数を作りたいのですが、Clang-Tidyにて警告の対象となってしまいます。
警告を受けないような連想配列の定数を作る方法はあるでしょうか。もし、これをご覧になった方で別の方法(連想配列で定数を定義する方法)をご存じの方は教えていただけませんか。
可能な限り、C++11の文法の範囲内を希望します。
サンプルコード
例えば、私のコードは次です。
c++11:FruitDatabase.cpp抜粋
#include <unordered_map> #include "FruitDatabase.h" namespace { /* * database変数はClang-Tidyの検査にて警告の対象となる。 * cert-err58-cpp * Clang-Tidy: Initialization of 'database' with static storage duration may throw an exception that cannot be caught */ const std::unordered_map<int, std::string> database = { {Fruit::Apple, "りんご"}, {Fruit::Orange, "みかん"}, {Fruit::Mango, "マンゴー"} }; }
Clang-Tidyの警告
Clang-Tidyの警告内容は次です。
Clang-Tidy: Initialization of 'database' with static storage duration may throw an exception that cannot be caught
cert-err58-cpp
という警告のようです。
所感
コンパイルエラーになるわけではないし、警告されているような問題を回避する処置はするつもりなので、この警告を無視してしまうこともできますが、私が無知ゆえに知らないところで大きな問題になるのも嫌です。
参考
環境
- C++11(GCC 4.8.5)
- Tidy 15.0(CLionビルトイン)
- Ubuntu 18.04
サンプルソース
c++11:FruitDatabaseクラス
#include <unordered_map> #include "FruitDatabase.h" namespace { /* * database変数はClang-Tidyの検査にて警告の対象となる。 * cert-err58-cpp * Clang-Tidy: Initialization of 'database' with static storage duration may throw an exception that cannot be caught */ const std::unordered_map<int, std::string> database = { {Fruit::Apple, "りんご"}, {Fruit::Orange, "みかん"}, {Fruit::Mango, "マンゴー"} }; // これでも同じ警告である。 // std::unordered_map<int, std::string> initialize() noexcept { // std::unordered_map<int, std::string> db; // try { // // } // catch (...) { // // } // return db; // } // // std::unordered_map<int, std::string> database = initialize(); } std::string FruitDatabase::name(Fruit::Code fruitCode) { auto it = database.find(fruitCode); if (it != database.end()) { return it->second; } return {}; }
c++11:Fruitクラス
#pragma once class Fruit { public: enum Code { Apple, Orange, Mango, }; explicit Fruit(Code code = Code::Apple) : _code{code} {} static int toInt(Code code) { return static_cast<int>(code); } int toInt() const { Fruit::toInt(_code); } Code code() const { return _code; } private: Code _code; };
c++11:利用
#include <iostream> #include "Fruit.h" #include "FruitDatabase.h" /* * Tidy cert_err58_cppのサンプル */ int main(int argc, char **argv) { Fruit fruit{Fruit::Apple}; auto fruit_name = FruitDatabase::name(fruit.code()); std::cout << "name is " << fruit_name << std::endl; return 0; }
まだ回答がついていません
会員登録して回答してみよう