为什么 GCC 在使用继承的构造函数时警告我无用的强制转换
Why is GCC warning me about a useless cast when using an inherited constructor?
请考虑以下C++代码:
#include <string>
struct A {
A(const std::string& s): s(s) {}
std::string s;
};
struct B: A {
using A::A;
};
int main() {
B b("test");
}
当我使用 -Wuseless-cast
参数通过 GCC 6.2.1 编译它时
g++ -std=c++14 -Wuseless-cast test.cpp -o test
它会发出以下警告:
test.cpp: In constructor ‘B::B(const string&)’:
test.cpp:9:14: warning: useless cast to type ‘const string& {aka const std::__cxx11::basic_string<char>&}’ [-Wuseless-cast]
using A::A;
^
test.cpp: In function ‘int main()’:
test.cpp:13:15: note: synthesized method ‘B::B(const string&)’ first required here
B b("test");
^
但是,当我将B
的定义更改为
struct B: A {
B(const std::string& s): A(s) {}
};
警告消失了。
问题:
- 为什么发出警告?
- 为什么为
B
指定构造函数而不是从A
继承构造函数可以修复警告?
您的示例可以进一步简化为:
struct A {
A(const int& i): i(i) {}
int i;
};
struct B: A {
using A::A;
};
int main() {
B b(0);
}
这是海湾合作委员会的一个悬而未决的问题。
显然不需要包含<string>
来重现它。请注意,该问题仍未得到证实,已知至少会影响GCC 6.1 - 通过查看您的问题,我会说它也影响GCC 6.2。
您可能面临一个已知的 GCC 错误 (PR 70844)。
相关文章:
- 警告处理为错误这里有什么问题
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- cppcheck在const std::string[]上引发警告
- GCC对可能有效的代码抛出init list生存期警告
- 如何在BST的这个简单递归实现中消除警告
- 关于std::move的使用,是否有编译警告
- g++ 在某个类成员未初始化时不发出警告
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 使用typeid警告未使用的变量
- 示例C++项目编译中的警告
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 如何修复编译器警告 C6386 和 C6385?
- 返回语句后的代码,没有警告
- 获取隐式转换溢出从无符号到已签名的警告
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 在未链接的部分上生成警告
- 警告 C4552:">>":未使用表达式的结果
- 抑制非平凡无用的警告"control may reach end of non-void function"
- 为什么C++中没有无用的条件回报警告
- 为什么 GCC 在使用继承的构造函数时警告我无用的强制转换