You can let g++
warn you about this use case with -Winit-self
(in conjunction with -Wuninitialized
), and if you treat warnings as errors, it should satisfy your itch.
This technique of using the copy constructor to self-initialize is sometimes used to suppress a global object's default constructor/initializer from executing. This may be necessary if the global object's default constructor is just to 0
initialize the object, but the object got used before the constructor would have been executed. As a throwback to C, globals are 0
initialized at program start, and then the C++ runtime begins to execute global constructors. For those narrow cases where the defined constructor that would have executed is only to 0
out the object, the self initialization does not do any harm.
In the general case, copy constructor self-initialization is bad practice, since it generally would cause the same sorts of problems that using an uninitialized variable would cause (that is, undefined behavior). In the particular example in the OP's question, i
is local to main
, and is therefore uninitialized. The result of reading an uninitialized variable is always undefined behavior.