Search code examples
c++autolist-initialization

Are the following initializations equivalent in C++


I read that often list-initialization is preferred over the 'old' way of using round braces, because they don't allow narrowing conversions. The auto keyword has similar attributes, in that it avoids conversions at all. I wonder whether the following two statements are equivalent:

auto a = SomeClass(arg_a, arg_b);
auto b = SomeClass{arg_a, arg_b};

That is, apart from the fact that b has a different name than a ;)

By equivalent, i mean that for whatever arguments SomeClass takes, in whatever situation, i can replace the expression leading to the construction of a, with the construction leading to the construction of b, provided of course that i am using the auto keyword. Is this the case, or are there any pitfalls/considerations?


Solution

  • They may or may not be the same, it depends on the type. For instance, if you have a std::vector then

    auto vec1 = std::vector<int>(1, 2);
    

    calls the constructor with the form of

    vector( size_type count,
            const T& value,
            const Allocator& alloc = Allocator());
    

    Which creates a vector of size 1 with the element having the value of 2. With

    auto vec1 = std::vector<int>{1, 2};
    

    the

    vector( std::initializer_list<T> init,
            const Allocator& alloc = Allocator() );
    

    constructor is called which creates a vector of size 2 containing the elements {1, 2}.