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..)
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).
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.
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.
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.
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.
Since it's purely a visibility issue, I can't imagine a plausible scenario where there would be a performance or memory penalty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With