C++11 Variable Initialization and Declaration

后端 未结 2 685
南笙
南笙 2021-01-15 23:05

With C++11 came a new way to initialize and declare variables.

Original

int c_derived = 0;

C++11

int modern{0};


        
相关标签:
2条回答
  • 2021-01-15 23:22

    Using braces was just an attempt to introduce universal initialization in C++11.

    Now you can use braces to initialize arrays,variables,strings,vectors.

    0 讨论(0)
  • 2021-01-15 23:29

    You're mistaken -- the int modern(0) form (with round brackets) was available in older versions of C++, and continues to be available in C++11.

    In C++11, the new form uses curly brackets to provide uniform initialisation, so you say

    int modern{0};
    

    The main advantage of this new form is that it can be consistently used everywhere. It makes it clear that you're initialising a new object, rather than calling a function or, worse, declaring one.

    It also provides syntactical consistency with C-style ("aggregate") struct initialisation, of the form

    struct A
    {
        int a; int b;
    };
    
    A a = { 1, 2 };
    

    There are also more strict rules with regard to narrowing conversions of numeric types when the curly-bracket form is used.

    0 讨论(0)
提交回复
热议问题