在自由功能中定义的类型,可通过外部自动访问。语言错误或功能? [英] type defined in free function, accessible through auto outside. Language Bug or Feature?
问题描述
让我们在自由函数中定义一个类,然后在外部进行访问:
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
名称MyType是正确隐藏:
如果我们替换为auto,则不会编译以下内容:
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;
}
标准怎么说?
如何预防?以下代码无济于事:
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;
}
推荐答案
标准未说具体而言,除了—正如您已经指出的—是具有范围而不是类型的 name 。使用 auto
绕过类型的名称,无论名称范围如何,您都可以使用该类型。
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.
有点类似于制作嵌套类 private
并不意味着您不能使用它的实例,只是您不能在封装类的范围之外命名它。
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.
我不知道您如何d阻止它,也不想这么做。
I don't see how you'd "prevent" it, nor why you'd want to.
这篇关于在自由功能中定义的类型,可通过外部自动访问。语言错误或功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!