Reputation: 38183
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..)
Upvotes: 32
Views: 24352
Reputation: 1988
You cannot use a locally defined structure for making an object of a templated type if some member functions are not invocable based on compile time constraints.
Example:
template<typename T>
concept C = requires(T t) { { t.unsupported() }; };
template <typename T>
struct X {
void unsupported() { static_assert(std::is_void_v<T>); }
};
static_assert(C<X<int>>);
template <typename T>
C auto make()
{
struct Y {
void unsupported() { static_assert(std::is_void_v<T>); }
};
return Y{};
}
int main()
{
C auto x = X<int>{}; // compiles fine
C auto y = make<int>(); // error: static assertion failed
return 0;
}
Upvotes: 0
Reputation: 16007
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.
Upvotes: 26
Reputation: 10695
I know you asked about performance, but I was wondering about another issue. Are you asking for both C and C++ or just one of those languages? I am taking a wild guess that you want to define a structure in a function for purposes of scope or hiding the structure.
For C, you can approach hiding things by defining and declaring structures in a separate module and making them static. Then, you can provide access functions, much as you would for members of a C++ class. You would include function declarations in a .h file for those modules that needed to access the structures.
If this is for C++, then creating a class and making the structure private or protected along with your writing the appropriate get/set/manipulate methods takes care of the rest.
If you edited your original post and expanded why you're asking this, you've asked a good question.
Upvotes: 0
Reputation: 3861
If you're using C++03, then technically you can't use a locally defined structure as a template argument but some compilers (namely MSVC) allow it.
Upvotes: 0
Reputation: 500893
Since it's purely a visibility issue, I can't imagine a plausible scenario where there would be a performance or memory penalty.
Upvotes: 6