=default ignores access specifier?

I found it quite odd that the following program still compiled fine despite the default constructor being private (4.8.1 g++):

 class A{
 private:
     A() = default;
     A(const A&) = default;
 };

 int main(){

     A a;

 }

Actually from 8.4.2[2] of the standard (N3242)

An explicitly-defaulted function may be declared constexpr only if it would have been implicitly declared as constexpr. If it is explicitly defaulted on its first declaration,

— it shall be public,

..........

What exactly is the purpose for the default specifier to ignore the access specification? I feel like that could cause an interface issue unwarranted by the class designer that didn't want users to create default values but needed the default constructor in the implementation. I thought that maybe it's because the default constructor is normally public and so the default aims to replicate it - but that doesn't answer why =default on the copy constructor doesn't ignore the private specification.

 class A{
 private:
     A() = default;
     A(const A&) = default;
 };

 int main(){

     A a;
     A b(a); //error: constexpr A::A(const A&) is private

 }

Actually I can't see from the standard where it mentions that explicitly-defaulted copy/move constructors/assignments aren't made public .


This is a gcc bug. Bug 57913 contains an example almost identical to yours. Bug 56429 contains links to several related bug reports, of which bug 54812 has been fixed in gcc 4.9, which indeed rejects your code.

error: 'constexpr A::A()' is private

Live demo

链接地址: http://www.djcxy.com/p/83738.html

上一篇: C ++

下一篇: = default忽略访问说明符?