Auto on Private Types
Using auto to declare a variable can be confusing when dealing with private class members. In this example, the code compiles successfully:
class Foo { struct Bar { int i; }; public: Bar Baz() { return Bar(); } }; int main() { Foo f; auto b = f.Baz(); std::cout << b.i; }
Is this code valid? If so, why?
The code is indeed valid. auto follows the same rules as template type deduction. The reason both auto b = f.Baz(); and fun(f.Baz()); compile is because the type of Foo::Bar is usable, even though its name is private.
Why is the type usable if its name is private?
The inaccessibility of private types extends only to their names. The types themselves can still be used, making it possible to return them to client code and pass them to template functions.
The above is the detailed content of Is Private Class Member Type Deduction with `auto` Valid in C ?. For more information, please follow other related articles on the PHP Chinese website!