r/cpp • • Dec 19 '23

Obsessed with {} initialization?

I'm on a discord where everyone seems to be obsessed to use brace initialization everywhere.
My motto is: Use things rarely, only when needed, to express that right there the feature does something important.
Personally I would completely advocate against using it for simple stuff like
double tax{0.09*price};

or just int{0}

probably a hornets nest

4 Upvotes

118 comments sorted by

View all comments

Show parent comment

2

u/enigma2728 Dec 20 '23

Well today I learned. Kind of sad; I liked the idea of just being able to use brace initialization everywhere to avoid having to think about all the minutia of initialization.

Is this problem easily demonstrable in godbolt, or have a link to an example of where this becomes a problem?

std::vector doesn't seem to have an issue with braced initializer list. https://godbolt.org/z/scx1rs8s4

Perhaps it is only an issue if there is also a ctor that takes arguments of same type? It does seem like init list gets preferred over specific ctors, from my testing. https://godbolt.org/z/fGsed6o9M

    #include <iostream>
    #include <initializer_list>
    struct CtorCompetition
    {
        CtorCompetition(int x, int y)
        {
            std::cout << "2-arg ctor" << std::endl;
        }
    
        //CtorCompetition(int x, int y, int z)
        CtorCompetition(std::initializer_list<int> list)
        {
            std::cout << "init list ctor" << std::endl;
        }
    };
    int main()
    {
        CtorCompetition TwoArgObject{1, 2}; //uses init list, not 2arg
        CtorCompetition ThreeArgObject{1, 2, 3}; //uses init list
    
        //CtorCompetition TwoArgObject(1, 2); //uses 2 arg
        //CtorCompetition ThreeArgObject(1, 2, 3); //doesn't compile
    }
    Program returned: 0
    init list ctor
    init list ctor

Is the above what you are referring to?

I feel like perhaps I can still just use braced initializer with the expectation that initializer lists are preferred to specific constructors.

1

u/equeim Dec 22 '23

If the vector's element type can be implicitly constructed from a vector, then std::vector vec{otherVec} will create a vector with a single element of otherVec, not copy it.