Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access a struct defined inside a function from outside the function through return type deduction?

Tags:

c++

c++14

I was watching one of Jason Turner's videos and I saw that you can define a type inside a function scope and have it available outside of that scope through function return type deduction.

auto f()
{
    struct MyStruct
    {
        int n;
    };
    return MyStruct{};
}

int main()
{
   auto a = f().n;
   return a;
}

Why is this allowed? Is there a paragraph in the C++ 14 standard that allows this?

When trying to get the typeid of MyStruct with clang in compile explorer I saw in the assembly output the type displayed as f()::MyStruct, so there is a scope, but somehow I can access MyStruct outside of that scope. Is this some kind of ADL thing?

like image 755
bluespeck Avatar asked Feb 21 '17 09:02

bluespeck


1 Answers

No, there's no ADL involved. Since your translation unit contains the definition of the structure, there's no problem in accessing its members.

The important point is that types don't really exist in scopes: names do. And notice that there's no way for you to use the identifier MyStruct instead of auto when declaring a. The name is as inaccessible as it should be. However, as long as you can get at the type without using the inaccessible name, all is fine.

In principle, this is hardly different from using a private member type:

class X
{
  struct Hidden
  {
    int i;
  };

public:
  Hidden get() const { return {42}; }
};

int main()
{
  X x;
  auto h = x.get();
  assert(h.i == 42);
}
like image 98
Angew is no longer proud of SO Avatar answered Oct 25 '22 04:10

Angew is no longer proud of SO