Advantages of passing std::intializer_list and to have overloads with it

68 Views Asked by At

Code example to have some context:

#include <vector>

class DatasetValue
{
public:
    using ValueType = int;
    using Values = std::vector<ValueType>;

    DatasetValue(Values values)
        : m_values{std::move(values)}
    {

    }

    const Values &values() const
    {
        return m_values;
    }

private:
    Values m_values;
};

int main()
{
    using Dataset = std::vector<DatasetValue>;

    auto dataset = Dataset{
        {{1, 2, 3, 4, 5}},
        {{7, 6, 5, 4, 3, 2, 1}},
        {{1, 2, 3, 4, 5, 6, 7, 8, 9}},
        {{3, 2, 1}},
        {{1}},
        {{ 4, 3, 2, 1}}
    };
}

So, we have some Dataset object that usually will be initialized with some predefined values on application startup and it works good.

However, then I've changed constructor parameter type to std::initilizer_list and noticed that size of generated binary is reduced by ~1 KB (in my environment, ARM Cortext M4 target). Considering that DatasetValue won't be initiliezed by lvalues or rvalues of containter_type now its constructor looks like:

DatasetValue(std::initializer_list<ValueType> values)
  : m_values{values} {}

We also can see something similiar on compiler explorer

So, my questions is:

Is it a good idea trying to provide constructor overloads that take std::initializer_list with/instead of (depending on context) lvalue or rvalue of container_type ones?

Notes:

  • Haven't tried it yet, but I'm interested in if this also give us some benefits with other containters (list, map, etc.). Will be happy to know your thoughts)
  • Update: Tests were done with no optiomization enabled (see comments)
0

There are 0 best solutions below