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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With