isocpp / isocpp/CppCoreGuidelines

C.48: Prefer default member initializers, also for non-constant initializers

Open
#2,332 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

The restriction "for constant initializers" on guideline C.48: Prefer default member initializers to member initializers in constructors for constant initializers appears unnecessary and undesirable.

For example, suppose a class has a creationTime member, that is initialized by now() in each of its constructors:

    class MyContainer {
        time_point<system_clock> creationTime;  // No default member initializer! Looks BAD to me.
        vector<int> data{};
    public:
        MyContainer() : creationTime{ system_clock::now() } {}
        explicit MyContainer(size_t n) : creationTime{ system_clock::now() }, data(n) {}
        MyContainer(initializer_list<int> values) : creationTime{ system_clock::now() }, data{ values } {}
    };


It appears preferable to use a default member initializer for MyContainer::creationTime, even though now() is not a constant. As follows:

    class MyContainer {
        time_point<system_clock> creationTime{ system_clock::now() };  // Preferable, right?
        vector<int> data{};
    public:
        MyContainer() = default;
        explicit MyContainer(size_t n) : data(n) {}
        MyContainer(initializer_list<int> values) : data{ values } {}
    };

In this example, using a default member initializer also avoids unnecessary code repetition, and it allows defaulting the default constructor.

In general, the guideline appears applicable to both constant and non-constant initializers.


  • Proposed fix: pull request #2333

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with guideline C.48 in the linked C++ Core Guidelines and review proposed fix pull request #2333. Done means the restriction to constant initializers is addressed so the guideline clearly covers the non-constant initializer example as well.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.