isocpp / isocpp/CppCoreGuidelines
C.48: Prefer default member initializers, also for non-constant initializers
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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