When I run the tools clang-tidy-3.8 and cppcheck-1.72, under the follow code:
#include <initializer_list>
#include <string>
#include <iostream>
using string_list = std::initializer_list<std::string>;
class Foo {
public:
explicit Foo(const string_list& strings) {
for (const auto& ss : strings) {
std::cout << ss << std::endl;
}
}
};
The clang-tidy-3.8 outputs:
$ > clang-tidy -checks='*' main.cpp -- -std=c++11
warning: initializer-list constructor should not be declared explicit [google-explicit-constructor] explicit Foo(const string_list& strings)
However, if I remove the keyword explicit, the cppcheck-1.72 reports:
$ > cppcheck main.cpp --language=c++ --std=c++11 --enable=all
(style) Class 'Foo' has a constructor with 1 argument that is not explicit.
I read at Google Cpp Guide:
Constructors that cannot be called with a single argument should usually omit explicit. Constructors that take a single std::initializer_list parameter should also omit explicit, in order to support copy-initialization (e.g. MyType m = {1, 2};).
Which tool is correct according the C++ standard?
that a constructor with only 1 argument has to be explicit
andthat a constructor with an initializer-list should not be explicit
, but cppcheck (1.73) does not have a test for initializer-list. So clang-tidy explicit relaxes the one argument rule for initializer-list. – t.nieseexplicit
keyword. Both variants of your code are equally conforming. These tools do not check conformance to the standard (the compiler does that), but to style guides - apparently, different ones. You keep saying thatcppcheck
enforces what you call "C++ rules" - but note how its message is clearly marked(style)
– Igor Tandetnik