Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 0.1.9 - is zero-initialization considered "dead code"?
#1
Consider the following example:

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!
Reply


Messages In This Thread
Rule 0.1.9 - is zero-initialization considered "dead code"? - by cgpzs - 25-09-2024, 07:22 AM

Forum Jump:


Users browsing this thread: 2 Guest(s)