0

Is there a performance difference in initializing the member variables in the following code? I used to think I should use the 'second' approach, as it initializes the variable to 2 while first will be initialzed to the default value (which will be zero) and then assigned to 1. But I am seeing the first approach everywhere, also at stackoverflow. So I wonder if they don't make a difference now in c++20?

class example
{
private:
int first = 1;
int second { 2 }
};
Thinium
  • 171
  • 1
  • 14
  • ***Is there a performance difference in initializing the member variables in the following code*** No. In most cases don't expect performance differences for builtin types. The optimizer is smart enough to generate the same optimized assembly code most of the time when there are differeces. – drescherjm Mar 06 '23 at 17:25
  • 1
    *while first will be initialzed to the default value (which will be zero) and then assigned to 1* **No**, that's not how it works. It gets initialized to `1`, not assigned. – Eljay Mar 06 '23 at 17:27
  • ***default value (which will be zero)*** Even without the initialization ithe members do not get initialized to 0 unless the `example` object is a global or static. In the case of a global or static the default initialization would only happen for the members that don't already have initialization in the constructor or class. – drescherjm Mar 06 '23 at 17:30

1 Answers1

1

There is no performance difference in you specific case. However, if the member variable type has only explicit constructors defined, you might not be able to use the = syntax to initialize it with a value. You might be still able to do T m_t = T{} if there is a move constructor available, but that could come with some additional computations for non-trivially-movable types. Moreover, if no move constructor is available, that would call the copy constructor (if it is available), and for non-trivially-copyable types that one has usually some bigger performance impact compared to the move one.

thebugger
  • 123
  • 6