[C++11] Unified list initialization ({} initialization)

Table of contents

1.1 {} initialization

2.2 std::initializer_list


        C++11 introduces a list initialization method for a unified initialization method, that is, using {} to initialize variables or structure variables. This article will introduce the list initialization method and std::initializer_list of c++11 in simple language .

1.1 {} initialization

        In c++98, it is actually allowed to use  {}  to uniformly initialize array or structure elements, such as:

struct Point
{
	int _x;
	int _y;

};
int main()
{
	int arrsy[] = { 1,2,3,4,5 };
	Point p = { 1,2 };

	return 0;
}

        In c++11,  the scope of use of {}  is expanded, so that {} can be applied to all built-in types and user-defined types, and it is also applicable to new expressions. When creating an object, you can also use the list initialization method for initialization. It should be noted that using the list initialization method to initialize the object will call the object's constructor . like:

struct Point
{
	int _x;
	int _y;

};

class student
{
public:
	student(string name,int age)
		:_name(name)
		,_age(age)
	{
		cout << name << " " << age;
	}
private:
	int _age;
	string _name;
};
int main()
{
	int a{ 1 };
	int* pa = new int[4]{0};

	student stu{ "Bob",19 };

	return 0;
}

2.2 std::initializer_list

        I think everyone will have questions  about how {}  initializes the object? In fact,  {}  will return a std::initializer_list object during initialization, as follows:

	auto pp = { 1,2,3 };
	cout << typeid(pp).name();

         When initializing the object variable, the std::initializer_list object is passed as a parameter into the constructor of the object to be initialized, and such a constructor is built into the c++11 container. Such as vector:

         Most of the containers in c++11 have added the constructor of std::initializer_list object as a parameter, which makes the initialization of the container very convenient, such as:

	vector<int> v = { 1,2,3,4 };
	map<string, string> dict = { {"delete","删除"},{"insert","插入"} };

Guess you like

Origin blog.csdn.net/qq_64293926/article/details/131873624