MikeLankamp / fpm

C++ header-only fixed-point math library
https://mikelankamp.github.io/fpm
MIT License
672 stars 85 forks source link

Constructor of fpm::fixed should be "= default" #36

Closed Eren121 closed 2 years ago

Eren121 commented 2 years ago

Currently, doing fixed_16_16 f {}; does not initialize f.m_value. The expected behaviour is to do zero-initialization, like int i{} initializes i to 0. The simple fix is to mark the constructor as default, which is good anyway.

Moreover, it can't be used in constexpr expressions:

constexpr void test()
{
    // fpm::fixed_16_16 f {}; // Error because can contain anything
    fpm::fixed_16_16 f{0}; // Ok
}

Also some of the operators like += are not marked constexpr but that's another issue.

MikeLankamp commented 2 years ago

Hi @Eren121, I was about to write how m_value was left default-initialized on purpose. The idea being that, like the float types that it replaces, default initialization means it has indeterminate value. This can have performance benefits when allocating large amounts of them and allows for a more natural replacement of floats with fpm::fixed.

However, in trying to prove my point with Godbolt, I learned that it doesn't work this way and that you're correct: default initializing an object (whether by itself or e.g. in a default-initializes std::array) with a defaulted default constructor still default initializes its members. But value initialization with a defaulted default constructor value-initializes its members, whereas value initialization with a user provided default constructor default-initializes it.

So thank you for this improvement!