문제

The following snippet is in a header file:

// Represents NxN scalar values (aka square matrix).  
template<std::size_t N>
class dummy
{ 
    public:
    float& operator[](const std::size_t ind) { return scalars[ind]; }

    private:
    float scalars[N*N];
};

using dummy2 = dummy<2>;

And this is how I would use it:

// 2x2=4 floats
dummy2 d;

std::cout << d[0] << std::endl; // prints 0
std::cout << d[1] << std::endl; // prints 0
std::cout << d[2] << std::endl; // prints -1.42253e+19
std::cout << d[3] << std::endl; // prints 4.59163e-41

My question is why do not the last two print calls result in a zero value?

도움이 되었습니까?

해결책

You didn't provide a constructor for your class, so the compiler generates a default one, which default-initialises all members of the class. And default-initialising a built-in type means it's not initialised at all, so any use of its value is undefined. In other words, scalars is not initialised to anything.

You can fix it like this:

template<std::size_t N>
class dummy
{ 
    public:
    float& operator[](const std::size_t ind) { return scalars[ind]; }

    dummy() : scalars()
    {}

    private:
    float scalars[N*N];
};

using dummy2 = dummy<2>;

This makes scalars value-initialised instead of default-initialised, and value-initialising a float sets it to 0.f, so everything will work.

Live example

다른 팁

scalars is not initialized explicitly. The first two zeros are actually the result of undefined behaviour, so you should set the array to zero in the constructor.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top