Inline Structure Declaration

I was interested to note that C ++ (VSVC ++ 2008 specifically) allows me to declare a struct inline in a method. eg:

MyClass::method() { struct test{ int x;}; test t = {99}; } 

My question is, how does this expression work domestically, and in particular does it have negative effects on productivity?

+6
source share
3 answers

how does this expression work inside?

Exactly the same as declaring in a namespace area, except that the name is displayed only within the scope in which it was declared (in this case, the function body). UPDATE: as @Nawaz points out, there are one or two additional restrictions that apply to local classes: they cannot have static data members, and (in C ++ 03, but not C ++ 11) they cannot be used as arguments of type template.

Does it have any negative consequences?

No, except for the scope (which affects only the compilation of code), it is identical to any other class definition.

+6
source

The main difference from the type definition inside the function area or outside it is the scope. That is, if it is defined inside a function, it will not be available outside the function.

There are other differences (at least in C ++ 03, I have not double-checked C ++ 11), you cannot have a static member or a member of a template in a local class. You cannot use this local class as an argument for a template (this restriction was removed in C ++ 11), and IIRC is because the local class has an internal binding (and not external to the namespace level class) and the required template arguments must have an external connection.

+2
source

If you think that a struct declaration in a function makes a negative value after each call and takes up processor time, you are mistaken. The compiler processes it at compile time, and it is how you declare a struct from a function (but a limited scope).

0
source

Source: https://habr.com/ru/post/899037/


All Articles