Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any "penalties" for defining a struct inside a function?

Just out of curiosity..

As the titles says: are there any "penalties" for defining a struct inside a function? (like performance, memory, bad programming practice, etc.)


P.S. I know, that it's a common practice to define (NON-template) functors inside functions, but still..)

like image 828
Kiril Kirov Avatar asked Jun 11 '12 12:06

Kiril Kirov


People also ask

Can you declare a struct inside a function?

Yes, the standard allows this, and yes, the name you create this way is only visible inside the function (i.e., it has local scope, just like when you define int i; , i has local scope).

Can you define a struct in a function C++?

A struct in C++ is a structure that allows defining user-defined data types using multiple primitive data types. There are multiple ways in which struct can be declared, initialized and used.

How do you use a struct inside a function?

You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.

Can you define a struct inside a class?

Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.


2 Answers

In C++11, no - there's no penalty. I would even consider it a very good style to not pollute any "more visible" scopes with you implementation details, unless, of course, you want to reuse that functor elsewhere. However, lambdas are essentially a condensed form of this idea, and should usually be preferred if you are just using the struct as functor. For all kinds of data, it is perfectly fine, although it usually competes with std::pair and std::tuple in that aspect.

In C++03, you cannot use such a struct as a template parameter, since those parameters need to have external linkage (Visual Studio lets you do it anyways, though). It can still be useful to use such a struct with a polymorphic interface.

like image 177
ltjax Avatar answered Sep 19 '22 11:09

ltjax


Since it's purely a visibility issue, I can't imagine a plausible scenario where there would be a performance or memory penalty.

like image 39
NPE Avatar answered Sep 21 '22 11:09

NPE