Why does this snippet using uniform initialization

2019-03-14 05:46发布

Note that derived uses C++11 uniform initialization syntax to call the base class constructor.

class base
{
    protected:
        base()
        {}
};

class derived : public base
{
    public:
        derived()
            : base{} // <-- Note the c++11 curly brace syntax
                     // using uniform initialization. Change the
                     // braces to () and it works.
        {}
};

int main()
{
    derived d1;

    return 0;
}

g++4.6 compiles this, however g++4.7 does not:

$ g++-4.7 -std=c++11 -Wall -Wextra -pedantic curly.cpp -o curly
curly.cpp: In constructor ‘derived::derived()’:
curly.cpp:4:13: error: ‘base::base()’ is protected
curly.cpp:19:24: error: within this context

What's going on?

Update 1: It also compiles without warnings with clang++-3.1
Update 2: Looks like a compiler bug for sure. It's apparently fixed in GCC 4.7.3.

4条回答
戒情不戒烟
2楼-- · 2019-03-14 06:03

compiling this with icpc ( intel compiler tested with version 11.1 -> 12.1) gives:

-bash-3.2$ icpc -std=c++0x test.c 
test.c(15): error: expected a declaration
          {}
          ^

test.c(12): error: expected a "("
              : base{} // <-- Note the c++11 curly brace syntax
                    ^

compilation aborted for test.c (code 2)

edit: but then again, c++11 is not fully implemented yet in icpc either http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler/

same as with g++ http://gcc.gnu.org/gcc-4.7/cxx0x_status.html

which clearly states it's still experimental, so a bug is very likely.

查看更多
Juvenile、少年°
3楼-- · 2019-03-14 06:10

I found this:

"The draft says that an initializer list initializing a reference is done not by direct binding, but by first constructing a temporary out of the element in the initializer list, and then binding the target reference to that temporary"

So it might be choking on the fact that the temporary created by base{} is being done through a protected constructor.

查看更多
贪生不怕死
4楼-- · 2019-03-14 06:19

It is probably because in version 4.7 C11 explicit override control was added.

查看更多
一纸荒年 Trace。
5楼-- · 2019-03-14 06:29

Paolo Carlini, a GCC/libstdc++ contributor, confirmed it is a bug/regression.

查看更多
登录 后发表回答