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

16,921

Solution 1

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.

Solution 2

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

Share:
16,921
Kiril Kirov
Author by

Kiril Kirov

SOreadytohelp

Updated on June 15, 2022

Comments

  • Kiril Kirov
    Kiril Kirov almost 2 years

    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..)