内联结构声明

发布于 2024-12-09 05:10:16 字数 185 浏览 0 评论 0原文

我有兴趣注意到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝天白云 2024-12-16 05:10:16

该声明在内部如何运作?

与命名空间范围内的声明完全相同,只不过该名称仅在其声明的块的范围内可见(在本例中为函数体)。更新:正如 @Nawaz 指出的那样,有一个或两个额外的限制适用于本地类:它们不能有静态数据成员,并且(在 C++03 中,但不是 C++11)它们不能用作模板类型参数。

它会对性能产生负面影响吗?

不,除了它的范围(只影响代码是否编译)之外,它与任何其他类定义相同。

how does this declaration work internally?

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.

does it have any negative performance implications?

No, apart from its scope (which only affects whether or not the code compiles), it is identical to any other class definition.

故人爱我别走 2024-12-16 05:10:16

与在函数作用域内部或外部定义类型的主要区别在于作用域。也就是说,如果它是在函数内部定义的,则在函数外部将无法访问它。

但还有其他差异(至少在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文