有没有办法在初始化字符串时避免来自 clang-tidy(fuchsia-default-arguments)的警告?

Is there a way to avoid this warning from clang-tidy (fuchsia-default-arguments) while initializing a string?

本文关键字:clang-tidy fuchsia-default-arguments 警告 初始化 字符串 有没有      更新时间:2023-10-16

考虑这段代码:

#include <iostream>
int main () { 
std::string str = "not default";
std::cout << str << std::endl;
return 0;
}

运行clang-tidy -checks=* string.cpp提供以下内容:

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).

是否有其他论点可以通过使此警告消失?我在这里并没有真正使用任何参数默认值。但是 std::string 的实现确实如此。

编辑:更改了代码以简化测试用例。

我在这里并没有真正使用任何参数默认值。但是 std::string 的实现确实如此。

字符串类定义了默认参数。但是,您通过调用构造函数而不显式传递第二个参数来使用默认参数。

是否有其他论点可以通过使此警告消失?

是的。如果您显式传递所有参数(包括默认参数(,则不会警告使用默认参数。在这种情况下,您需要传递的参数是字符串构造函数的第二个参数,正如警告消息所指出的那样。它是字符串的分配器。它具有类型std::allocator<char>.

请注意,为了在复制初始化表达式中传递多个参数,您需要使用大括号的初始化列表:

std::string str = {
"actually not default",
std::allocator<char>(),
};

也就是说,使用默认参数通常不被认为是一种不好的做法,你可以说,保持使用并禁用警告可能会更好。但情况是否如此,主要取决于意见。奇怪的是,警告名称和文档都暗示警告是针对 fuchsia 代码库的,但 fuchsia 文档明确允许使用默认参数(但建议使用"判断"(。