J. Daniel
J. Daniel

Reputation: 383

c++ initializers list std::array best performance

Given this class:

template<class value_type, std::size_t row_count, std::size_t column_count>
class matrix 
{
public:
    matrix()
    {
    }

    matrix(std::array<std::array<value_type, row_count> ,column_count> matrix_data)
        : data(matrix_data) {}

    void 
    insert(std::size_t row, std::size_t column, value_type value)
    {
        data[row][column] = value;
    }

    value_type 
    get(std::size_t row, std::size_t column) const
    {
        return data[row][column];
    }

private:
    // Initialised to zero
    std::array<std::array<value_type, row_count>, column_count> data{};
};

The data array gets initialised to zero. But if I would use the second constructor (non default one) it would overwrite it with other values.

Is there a way to improve the performance so the values only get intialised to zero when the first constructor is used? Im guessing a for loop is less efficient than the data{} statement? Am I right?

Thanks

Upvotes: 0

Views: 117

Answers (1)

NathanOliver
NathanOliver

Reputation: 180595

When you have a class member like

std::array<std::array<value_type, row_count>, column_count> data{};

what you are saying is that in all constructors that do not initialize data use data{} as the initializer. If you have a constructor that provides a member initializer for data then the compiler will use that initializer instead of the default you provided. That means in

matrix(std::array<std::array<value_type, row_count> ,column_count> matrix_data)
    : data(matrix_data) {}

that data will be copy initialized from matrix_data and there is no zero initialization step.

Upvotes: 2

Related Questions