logoalt Hacker News

spacechild1 • today at 4:46 PM • 2 replies • view on HN

The example is pretty contrived because in practice you'd want to zero-initialize the members in the default constructor anyway.

    struct span {
        const char *p = nullptr;
        size_t len = 0;
        span() = default; // or span() {}
        span(const char *s, size_t n) : p(s), len(n) {}
    };
In that case, there is no difference between

    span s;
and

    span s{};
There are only few use cases where you want a default constructor that does not initialize its members. One example are wrappers around primitive types where you want to closely preserve the original semantics. Whether that's a good idea in the first place really depends on the use case.

For example, std::atomic used to default-initialize the underlying value, which led to many bugs in user code. Since C++20 std::atomic uses value-initialization. See https://cplusplus.github.io/LWG/issue2334. On the one hand, std::atomic is now safer to use, on the other hand, it is not an implicit-lifetime-type anymore, which means you can't put it in shared memory without UB...

Another example is glm::vec, which has actually hit me a few times in my own code. At least they recognized the issue and allowed to override the default behavior with the GLM_FORCE_CTOR_INIT define.


Replies

dako2117 • today at 7:12 PM

I believe there are also cases where you have a member variable which has a complicated initialization that you may want to handle in some sort of manner that is not appropriate for the default ctor. So you may not want to initialize everything right away in this scenario.

➕ show 1 reply
jacobcmarshall • today at 6:37 PM

This is one of the core problems with C++. If you ever encounter a language oddity, it's because you're holding the language wrong, and if you just do it The Right Way, you won't have this problem.

C++ rarely pushes the user towards doing the right thing.