25-09-2024, 07:22 AM
Consider the following example:
Does that violate Rule 0.1.9? While the initialization may be redundant, it serves a purpose as defensive programming. If we remove the zero-initialization, we risk having some members of "Foo" uninitialized, especially if we bump to a new version of "third_party.h" that adds a new member to the struct. It's safer to zero-initialize at the declaration, to ensure no members remain uninitialized.
It's also preferable to initialize like this instead of "Foo f{123, 321};", because we can see written in code which field gets which value. We need to wait until C++20 to get designated initializers in C++ to initialize everything in one line.
Thanks!
Code:
// third_party.h
struct Foo
{
int32_t a;
int32_t b;
};
// client.cpp
Foo create()
{
Foo f{}; // Violates Rule 0.1.9?
f.a = 123;
f.b = 321;
return f;
}
Does that violate Rule 0.1.9? While the initialization may be redundant, it serves a purpose as defensive programming. If we remove the zero-initialization, we risk having some members of "Foo" uninitialized, especially if we bump to a new version of "third_party.h" that adds a new member to the struct. It's safer to zero-initialize at the declaration, to ensure no members remain uninitialized.
It's also preferable to initialize like this instead of "Foo f{123, 321};", because we can see written in code which field gets which value. We need to wait until C++20 to get designated initializers in C++ to initialize everything in one line.
Thanks!