开发者

Inline struct declaration

开发者 https://www.devze.com 2023-04-11 23:16 出处:网络
I was interested to note that C++ (VSVC++ 2008 specifically) lets me declare a struct inline in a method.

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 performanc开发者_如何学Pythone implications?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号