为什么 GCC 在使用继承的构造函数时警告我无用的强制转换



请考虑以下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)。

最新更新