问题
Consider this piece of code:
#include <iostream>
int main () {
std::string str = "not default";
std::cout << str << std::endl;
return 0;
}
Running clang-tidy -checks=* string.cpp
gives the following:
7800 warnings generated.
/tmp/clang_tidy_bug/string.cpp:4:21: warning: calling a function that uses a default argument is disallowed [fuchsia-default-arguments]
std::string str = "not default";
^
/../lib64/gcc/x86_64-pc-linux-gnu/8.1.1/../../../../include/c++/8.1.1/bits/basic_string.h:509:39: note: default parameter was declared here
basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
^
Suppressed 7799 warnings (7799 in non-user code).
Is there some other argument that can be passed to make this warning go away? I am not really using any argument defaults here. But the implementation of std::string does.
Edit: Changed the code to simplify the test case.
回答1:
I am not really using any argument defaults here. But the implementation of std::string does.
The string class defined the default argument. But you used the default argument by calling the constructor without passing the second argument explicitly.
Is there some other argument that can be passed to make this warning go away?
Yes. If you pass all arguments explicitly (including defaulted ones), then nothing is going to warn about using the default arguments†. The argument that you need to pass in this case is the second argument of the string constructor, as helpfully pointed out by the warning message. It is the allocator for the string. It has the type std::allocator<char>
.
Note that in order to pass more than one argument in copy-initialization expression, you need to use a braced-init-list:
std::string str = {
"actually not default",
std::allocator<char>(),
};
† That said, it isn't generally considered a bad practice to use default arguments, and you might arguably be better off by keeping the use and disabling the warning instead. But whether that's the case, is mostly based on opinion. Strangely enough, both the warning name, and documentation imply that the warning is intended for the fuchsia codebase, yet fuchsia docs explicitly allow the use of default arguments (but suggests using "judgement").
来源:https://stackoverflow.com/questions/51217635/is-there-a-way-to-avoid-this-warning-from-clang-tidy-fuchsia-default-arguments