Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc bug? It inexplicably decays array to pointer, while clang does not

This is a simplified version which illustrate the problem:

struct Foo {
    Foo() = default;

    template <std::size_t N>
    Foo(const char(&)[N]) {}
};

template <std::size_t N>
auto foo(const char (&arr)[N]) -> Foo
{
    return arr;
}

auto main() -> int
{
    foo("Stack Overflow");
}

g++ seems to decay arr to const char *, although an array reference argument is passed to an array reference parameter . It gives this error:

In instantiation of Foo foo(const char (&)[N]) [with long unsigned int N = 4ul]:

error: could not convert (const char*)arr from const char* to Foo

 return arr;
        ^

While clang++ behaves how I expect and compiles the code.

The code compiles fine on gcc with any of those modifications:

return {arr};
return Foo(arr);
return (Foo)arr;
return static_cast<Foo>(arr);

Is it a gcc bug?

Tried it with all g++ and clang++ versions which support c++14.(*)

(*) I just tried it with a snapshot of gcc 6 and it compiles OK. So it does look like a bug fixed in gcc 6

like image 279
bolov Avatar asked Mar 13 '16 12:03

bolov


1 Answers

Yes, this was a bug in GCC where arrays would decay into pointers prematurely and the converting constructor would no longer appear to be a viable candidate. Examples similar to yours (and the eventual fix) can be found in the comments of these two bug reports:

  • https://gcc.gnu.org/bugzilla/show_bug.cgi?id=41426
  • https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66895
like image 105
一二三 Avatar answered Oct 24 '22 05:10

一二三