type defined in free function, accessible through auto outside. Language Bug or Feature?

删除回忆录丶 提交于 2019-12-20 01:55:08

问题


Let's define a class inside a free function, and access it outside:

#include <iostream>
auto myFunc(){
    class MyType{public: int i = 0; int j = 1;};
    return MyType();
}
int main() {
    auto my_type = myFunc();
    std::cout << my_type.i << " " << my_type.j << "\n";
    return 0;
}

It compiles, run as expected:

0 1

The name MyType is properly hidden: if we replace auto, the following won't compile:

int main() {
    MyType my_type = myFunc();
    std::cout << my_type.i << " " << my_type.j << "\n";
    return 0;
}

What does the standard say about it?

How to prevent it? The following code did not help:

 namespace{
auto myFunc(){
    class MyType{public: int i = 0; int j = 1;};
    return MyType();
}
}
int main() {
    auto my_type = myFunc();
    std::cout << my_type.i << " " << my_type.j << "\n";
    // your code goes here
    return 0;
}

回答1:


The standard doesn't say anything about this specifically, except that — as you've already pointed out — it's the name that has a scope, not the type. Use of auto bypasses the type's name, giving you a way to get at the type regardless of the name's scope.

It's kind of similar to how making a nested class private doesn't mean you can't use instances of it, only that you can't name it outside of the encapsulating class's scope.

I don't see how you'd "prevent" it, nor why you'd want to.



来源:https://stackoverflow.com/questions/33783513/type-defined-in-free-function-accessible-through-auto-outside-language-bug-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!