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

时间:2017-01-31 07:49:33

标签: c++ 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继承构造函数来修复警告?

2 个答案:

答案 0 :(得分:6)

您的示例可以进一步简化为:

struct A {
    A(const int& i): i(i) {}
    int i;
};

struct B: A {
    using A::A;
};

int main() {
    B b(0);
}

这是海湾合作委员会的open issue 显然不需要包含<string>来重现它。 请注意,该问题仍然未经证实,并且已知至少影响GCC 6.1 - 通过查看您的问题,我会说它也会影响GCC 6.2。

答案 1 :(得分:4)

您可能面临已知的GCC错误(PR 70844)。