内联结构声明
我有兴趣注意到 C++(特别是 VSVC++ 2008)允许我在方法中声明内联结构。 例如:
MyClass::method()
{
struct test{ int x;};
test t = {99};
}
我的问题是,这个声明在内部如何工作,具体来说它是否有任何负面的性能影响?
I was interested to note that C++ (VSVC++ 2008 specifically) lets me declare a struct inline in a method.
e.g:
MyClass::method()
{
struct test{ int x;};
test t = {99};
}
My question is, how does this declaration work internally, and specifically does it have any negative performance implications?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与命名空间范围内的声明完全相同,只不过该名称仅在其声明的块的范围内可见(在本例中为函数体)。更新:正如 @Nawaz 指出的那样,有一个或两个额外的限制适用于本地类:它们不能有静态数据成员,并且(在 C++03 中,但不是 C++11)它们不能用作模板类型参数。
不,除了它的范围(只影响代码是否编译)之外,它与任何其他类定义相同。
Exactly like a declaration at namespace scope, except that the name is only visible within the scope of the block it's declared in (in this case, the function body). UPDATE: as @Nawaz points out, there are one or two extra restrictions that apply to local classes: they cannot have static data members, and (in C++03, but not C++11) they can't be used as template type arguments.
No, apart from its scope (which only affects whether or not the code compiles), it is identical to any other class definition.
与在函数作用域内部或外部定义类型的主要区别在于作用域。也就是说,如果它是在函数内部定义的,则在函数外部将无法访问它。
但还有其他差异(至少在 C++03 中,我没有重新检查 C++11),本地类中不能有静态成员或模板成员。您也不能使用该本地类作为模板的参数(此限制已在 C++11 中删除),IIRC 这是因为本地类具有内部链接(而不是命名空间级别类的外部链接),并且需要模板外部链接的参数。
The main difference from defining the type inside the function scope or outside of it is, well, the scope. That is, if it is defined inside the function it will not be accessible outside of the function.
There are other differences though (at least in C++03, I have not rechecked C++11), you cannot have a static member or a template member in a local class. You cannot use that local class as argument to a template either (this limitation has been removed in C++11), and IIRC this is because the local class has internal linkage (rather than external for a namespace level class), and templates required the arguments to be of external linkage.