Why can I use auto on a private type?

前端 未结 4 708
悲哀的现实
悲哀的现实 2020-11-22 09:26

I was somehow surprised that the following code compiles and runs (vc2012 & gcc4.7.2)

class Foo {
    struct Bar { int i; };
public:
    Bar Baz() { retu         


        
4条回答
  •  旧巷少年郎
    2020-11-22 09:51

    To add to the other (good) answers, here's an example from C++98 that illustrates that the issue really doesn't have to do with auto at all

    class Foo {
      struct Bar { int i; };
    public:
      Bar Baz() { return Bar(); }
      void Qaz(Bar) {}
    };
    
    int main() {
      Foo f;
      f.Qaz(f.Baz()); // Ok
      // Foo::Bar x = f.Baz();
      // f.Qaz(x);
      // Error: error: ‘struct Foo::Bar’ is private
    }
    

    Using the private type isn't prohibited, it was only naming the type. Creating an unnamed temporary of that type is okay, for instance, in all versions of C++.

提交回复
热议问题