Is initializing with “var{args}” a new feature of C++0x, or merely syntactic sugar?

后端 未结 3 1046
再見小時候
再見小時候 2021-01-20 05:18

I was reading the C++0x faq and came across the section detailing initializer lists. The examples were mostly variations of:

vector vi = { 1, 2,          


        
3条回答
  •  庸人自扰
    2021-01-20 06:03

    The uniform initialization prevents narrowing conversions i.e. conversions that would cause loss of data:

    #include 
    
    std::vector v{1.0F, 2.0F, 3.0F}; // OK: 
    
    std::vector w{1.0, 2.0, 3.0}; // OK: doubles could be put into floats without loss.
    
    std::vector j{1.1, 2.2, 3.3}; // error: narrowing
    
    std::vector k{1L, 2L, 3L}; // OK: the long numbers can be represented as int without loss.
    
    std::vector l{0xfacebeefL, 0xdeadbabeL, 0xfadecabeL}; // error: narrowing.
    

提交回复
热议问题