Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline struct declaration

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?

like image 429
Mr. Boy Avatar asked Oct 11 '11 09:10

Mr. Boy


People also ask

What is the declaration of the struct?

The struct-declaration-list specifies the types and names of the structure members. A struct-declaration-list argument contains one or more variable or bit-field declarations. Each variable declared in struct-declaration-list is defined as a member of the structure type.

How do you declare a struct in C++?

The struct keyword defines a structure type followed by an identifier (name of the structure). Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure. For example: struct Person { char name[50]; int age; float salary; };

Can you declare in a struct?

Structure members cannot be initialized with declaration.

Can you forward declare a struct?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).


2 Answers

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.

like image 149
Mike Seymour Avatar answered Oct 06 '22 17:10

Mike Seymour


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.

like image 42
David Rodríguez - dribeas Avatar answered Oct 06 '22 16:10

David Rodríguez - dribeas