Why use initializer_list instead of vector in parameters?

后端 未结 3 2151

What is the actual benefit and purpose of initializer_list, for unknown number of parameters? Why not just use vector and be done with it?

In f

3条回答
  •  轮回少年
    2021-01-30 21:36

    Well, std::vector has to use initializer_list to get that syntax as it obviously can't use itself.

    Anyway, initializer_list is intended to be extremely lightweight. It can use an optimal storage location and prevent unnecessary copies. With vector, you're always going to get a heap allocation and have a good chance of getting more copies/moves than you want.

    Also, the syntax has obvious differences. One such thing is template type deduction:

    struct foo {
        template  
        foo(std::initializer_list) {}
    };
    
    foo x{1,2,3}; // works
    

    vector wouldn't work here.

提交回复
热议问题