Even though so many people consider initializing at the time of definition a good idea, but there's a reason for it being possible in C++.
That reason is exactly the additional redundant assignment. But you only need to worry about it when bar
is not just an int
and has a much heavier constructor because:
- the compiler optimizes away that redundant assignment sometimes.
- default initialization usually low cost; but of course that should be checked
So it all comes back to bar
being costly to initialize or not.
If it is, I suggest you to not default initialize instead, try to initialize it in your member initializer list if doing so is:
- possible, and
- doesn't throw errors or you are at least know a way to catch the exceptions
and if that's not a good idea, then I suggest using pointers or references to not initialize at all and use a member function to do so when it's necessary;
and if that's not a good idea either, then I suggest doing the assignment in the constructor of your struct but try to make the default initialization of your bar
a not-that-much-costly as possible.
You also need to consider the when you're initializing this object. If your program is a long-running software, then just initialize it at start-up if possible; but of course these situations require more details about the program itself.
I suggest reading the C++ Core Guidelines for more details.