CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

I.22 Various issues

Open eisenwave opened this issue 2 years ago • 0 comments

Firstly, the explanation in I.22 says that one of the initializations access an uninitialized object. I believe that this is not correct, and instead, a zero-initialized object is accessed.

It's somewhat unclear whether "complex initialization" is supposed to mean dynamic initialization, though I would assume that it is intended to.

Dynamic initialization is not a problem in principle, and it can be quite beneficial. For example:

inline const std::array<double, 128> sin_table = [] {
    decltype(sin_table) result;
    for (std::size_t = 0; i < sin_table.size(); ++i) {
        result[i] = std::sin(std::numbers::pi * 2 * i / sin_table.size());
    }
    return sin_table;
}();

Until C++26, sin_table could not be constexpr, yet it's entirely reasonable and even best practice to use dynamic initialization, since the only alternative is hand-writing the initializer-list, or writing your own constexpr sin function1). Neither of these are very practical.

1)This would be a solution because only non-constexpr functions are meant to be flagged by the current Enforcement standards

Suggested Solution

(Easy) use zero-initialization and dynamic initialization correctly in the current wording, and add an exception for dynamic initialization that only accesses objects within the current TU, or functions which act as a "pseudo-constructor", such as the lambda above.

(Hard) additionally reword the rule in terms of Avoid dynamic initialization which relies on objects in other translation units

eisenwave avatar Aug 13 '23 14:08 eisenwave