Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GCC warning me about a useless cast when using an inherited constructor?

Tags:

c++

gcc

Consider the following C++ code:

#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");
}

When I compile it via GCC 6.2.1 with the -Wuseless-cast parameter

g++ -std=c++14 -Wuseless-cast test.cpp -o test

it emits the following warning:

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");
              ^

However, when I change the definition of B to

struct B: A {
    B(const std::string& s): A(s) {}
};

the warning goes away.

Questions:

  • Why is the warning emitted?
  • Why does specifying a constructor for B instead of inheriting it from A fixes the warning?
like image 421
s3rvac Avatar asked Jan 31 '17 07:01

s3rvac


2 Answers

Your example can be further reduced to:

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

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

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

That is an open issue on GCC.
Including <string> isn't apparently required to reproduce it. Note that the issue is still unconfirmed and it is known to affect at least GCC 6.1 - by looking at your question I would say that it affects also GCC 6.2.

like image 163
skypjack Avatar answered Oct 11 '22 02:10

skypjack


You are probably facing a known GCC bug (PR 70844).

like image 22
yugr Avatar answered Oct 11 '22 03:10

yugr