C++

Curly brace initialization for C++ 11 new features


This article mainly introduces the new C++11 features of curly brace initialization related content, to share for your reference to learn, the following words do not say, to 1 look at the detailed introduction:

Before C++11, C++ has the following initialization methods:

// The parentheses are initialized
string str("hello");

// Equals initialization
string str="hello";

// Curly brace initialization
struct Studnet{
 char* name;
 int age;
};
Studnet s={"dablelv",18}; // Pure data ( Plain of Data,POD ) type object
Studnet sArr[]={{"dablelv",18},{"tommy",19}}; //POD An array of

While c++03 provides a variety of object initializations, it does not provide curly brace initializations for custom type objects, nor does it initialize the POD array when new[] is used.

Fortunately, C++11 extends curly brace initialization to compensate for C++03.

class Test{
 int a;
 int b;
public:
 C(int i, int j);
};
Test t{0,0};     //C++11 only , which is equivalent to  Test t(0,0);
Test* pT=new Test{1,2};   //C++11 only , which is equivalent to  Test* pT=new Test{1,2};
int* a = new int[3]{ 1, 2, 0 }; //C++11 only

In addition, the C++11 curly brace initialization can also be applied to the container and can finally be freed push_back() Called, C++11 can intuitively initialize the container:

// C++11 container initializer
vector<string> vs={ "first", "second", "third"};
map<string,string> singers ={ {"Lady Gaga", "+1 (212) 555-7890"},{"Beyonce Knowles", "+1 (212) 555-0987"}};

Therefore, it is possible to initialize the braces provided by C++11 into a unified 1 initialization mode, which not only reduces the difficulty of memory, but also improves the uniformity of the code by 1 degree.

In addition, in C++11, the data member of the class can be directly assigned a default value when stating:

class C
{
private:
 int a=7; //C++11 only
};

conclusion

reference

[1]C++ 11 new features