Before C++11,there was no easy way to do things like initialize a std::vector or std::map(or a custom container) to a set of values. You could do so for an old C-style array, but not easily for STL collections. Initializer Lists provide a solution to this problem. Thus, like with the auto keyword, they work to remove a lot of the verbosity that has traditionally attached with using the STL collection classes.

Uniform Initialization expands on the Initializer List syntax, to provide a syntax that allows for fully uniform type initialization that works on any object --removing the distinction between initialization of aggregate + non-aggregate classes, arrays, STL/custom collection classes, and PODs.

To support initializer list in a class (i.e. if creating your own collection), you simply define a constructor that takes a std::initializer_list as its parameter, which can then be used like a collection.

C++11引入了初始化列表来初始化变量和对象。自定义类型,如果想用初始化列表就要包含initializer_list头文件。

C++11将使用大括号的初始化(列表初始化)作为一种通用初始化方式,可用于所有类型。初始化列表不会进行隐式转换。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "init_list.hpp"
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <set>

///////////////////////////////////////////
// reference: http://en.cppreference.com/w/cpp/language/list_initialization
struct Foo {
	//std::vector<int> mem = { 1, 2, 3 }; // list-initialization of a non-static member
	//std::vector<int> mem2;
	//Foo() : mem2{ -1, -2, -3 } {} // list-initialization of a member in constructor
};

std::pair<std::string, std::string> f(std::pair<std::string, std::string> p)
{
	return{ p.second, p.first }; // list-initialization in return statement
}

int test_init_list1()
{
	int n0{};     // value-initialization (to zero)
	int n1{ 1 };    // direct-list-initialization
	std::string s1{ 'a', 'b', 'c', 'd' }; // initializer-list constructor call
	std::string s2{ s1, 2, 2 };           // regular constructor call
	std::string s3{ 0x61, 'a' }; // initializer-list ctor is preferred to (int, char)

	int n2 = { 1 }; // copy-list-initialization
	double d = double{ 1.2 }; // list-initialization of a temporary, then copy-init

	std::map<int, std::string> m = { // nested list-initialization
			{ 1, "a" },
			{ 2, { 'a', 'b', 'c' } },
			{ 3, s1 }
	};

	std::cout << f({ "hello", "world" }).first << '\n'; // list-initialization in function call

	const int(&ar)[2] = { 1, 2 }; // binds a lvalue reference to a temporary array
	int&& r1 = { 1 }; // binds a rvalue reference to a temporary int
	//  int& r2 = {2}; // error: cannot bind rvalue to a non-const lvalue ref

	//  int bad{1.0}; // error: narrowing conversion
	unsigned char uc1{ 10 }; // okay
	//  unsigned char uc2{-1}; // error: narrowing conversion

	Foo f;

	std::cout << n0 << ' ' << n1 << ' ' << n2 << '\n'
		<< s1 << ' ' << s2 << ' ' << s3 << '\n';
	for (auto p : m)
		std::cout << p.first << ' ' << p.second << '\n';
	//for (auto n : f.mem)
	//	std::cout << n << ' ';
	//for (auto n : f.mem2)
	//	std::cout << n << ' ';

	return 0;
}

////////////////////////////////////////////
// reference: https://mbevin.wordpress.com/2012/11/16/uniform-initialization/
int test_init_list2()
{
	int arr[]          { 1, 2, 3, 4, 5 };
	std::vector<int> v{ 1, 2, 3, 4, 5 };
	std::set<int> s{ 1, 2, 3, 4, 5 };
	std::map<int, std::string> m{ { 0, "zero" }, { 1, "one" }, { 2, "two" } };

	return 0;
}

///////////////////////////////////////////////////////
// reference: https://mbevin.wordpress.com/2012/11/16/uniform-initialization/
// 'aggregate' class - no user-declared constructor, no private/protected members, no base, no virtual function
struct ClassA {
	int x;
	double y;
};

// non-aggregate class
class ClassB {
private:
	int x;
	double y;
public:
	ClassB(int _x, double _y) :x(_x), y(_y) {}
};

std::pair<double, double> multiplyVectors(
	std::pair<double, double> v1,
	std::pair<double, double> v2) {
	return{ v1.first*v2.first, v1.second*v2.second };
}

int test_init_list3()
{
	int i{ 3 };
	int j{}; // empty braces initialize the object to it's default (0)
	std::string s{ "hello" };

	ClassA objA1{};
	ClassA objA2{ 1, 2.0 };
	ClassB objB1{ 1, 2.0 };
	ClassA arrOfAs[] = { { 1, 1.0 }, { 2, 2.0 }, { 3, 3.0 } };

	// ouch, the theory is that this should work in C++11, however this doesn't compile, at least with clang, comments?
	ClassB arrOfBs[] = { { 1, 1.0 }, { 2, 2.0 }, { 3, 3.0 } };

	// however, this does work
	std::vector<ClassB> vectorOfBs = { { 1, 1.0 }, { 2, 2.0 }, { 3, 3.0 } };

	auto result = multiplyVectors({ 1.0, 2.0 }, { 3.0, 4.0 });

	return 0;
}

GitHubhttps://github.com/fengbingchun/Messy_Test

C++11中initializer lists的使用的更多相关文章

  1. C++11 中值得关注的几大变化(网摘)

    C++11 中值得关注的几大变化(详解) 原文出处:[陈皓 coolshell] 源文章来自前C++标准委员会的 Danny Kalev 的 The Biggest Changes in C++11 ...

  2. C++11 中值得关注的几大变化(详解)

    源文章来自前C++标准委员会的 Danny Kalev 的 The Biggest Changes in C++11 (and Why You Should Care),赖勇浩做了一个中文翻译在这里. ...

  3. C++ 11中几个我比较喜欢的语法(二)

    之前在文章C++ 11中几个我比较喜欢的语法中介绍了几个我比较喜欢的C++语法,其中有些语法由于VC 11还不支持,无法跨平台,所以没有介绍.前几天VS 2013 Preview发布后,对C++ 11 ...

  4. 从linux0.11中起动部分代码看汇编调用c语言函数

    上一篇分析了c语言的函数调用栈情况,知道了c语言的函数调用机制后,我们来看一下,linux0.11中起动部分的代码是如何从汇编跳入c语言函数的.在LINUX 0.11中的head.s文件中会看到如下一 ...

  5. C++ 11 中的右值引用

    C++ 11 中的右值引用 右值引用的功能 首先,我并不介绍什么是右值引用,而是以一个例子里来介绍一下右值引用的功能: #include <iostream>    #include &l ...

  6. IOS中的Block与C++11中的lambda

    ios中的block 可以说是一种函数指针,但更确切的讲,其实际上其应该算是object-c对C++11中lambda的支持或者说是一个语言上的变体,其实际内容是一样的,C++的lambda我已经有简 ...

  7. 在Windows 8.1及IE 11中如何使用HttpWatch

    提示:HttpWatch现已更新至v9.1.8,HttpWatch v9.1及以上的版本现都已支持Windows 7,8,8.1和IE 11. 如果你的HttpWatch专业版授权秘钥允许进入vers ...

  8. C++11中对类(class)新增的特性

    C++11中对类(class)新增的特性 default/delete 控制默认函数 在我们没有显式定义类的复制构造函数和赋值操作符的情况下,编译器会为我们生成默认的这两个函数: 默认的赋值函数以内存 ...

  9. callable object与新增的function相关 C++11中万能的可调用类型声明std::function<...>

    在c++11中,一个callable object(可调用对象)可以是函数指针.lambda表达式.重载()的某类对象.bind包裹的某对象等等,有时需要统一管理一些这几类对象,新增的function ...

随机推荐

  1. 从产品展示页面谈谈Hybris系列之二: DTO, Converter和Populator

    文章作者:张健(Zhang Jonathan) 上一篇文章 从产品展示页面谈谈Hybris的特有概念和设计结构 我们讲解了Hybris一些特有的概念以及大体架构,并且介绍了Facade层里是如何定义D ...

  2. 关于c++对文件读写的封装

    namespace { UINT_T GetWriteSizeForNoBuf(UINT_T fsize) { UINT_T write_buf_size = ; == ) { write_buf_s ...

  3. Netbackup用于技术支持的问题报告(报障模版)

    在与支持部门联系以报告问题之前,请填写以下信息. 日期: _________________________记录以下产品.平台和设备信息:■ 产品及其版本级别.■ 服务器硬件类型和操作系统级别.■ 客 ...

  4. ProjectServer任务审批后自动发布

    我们知道ProjectServer汇报工时的顺序是这样: 1.项目成员打开自己的时间表,选择要汇报的任务,在汇报工时栏填写实际工时. 2.汇报工时后点击保存. 3.将汇报工时的任务提交给项目经理. 4 ...

  5. 重写equals方法(未完)

    equals方法是我们日常编程中很常见的方法,Object中对这个方法的解释如下: boolean equals(Object obj) 指示其他某个对象是否与此对象“相等”. 查看该方法的底层代码如 ...

  6. 记录一次LOB损坏导致的EXPDP导出ORA-01555报错

    同事导出数据,结果遇到如下报错: expdp user1/XXXXXXXX directory=szdata1 dumpfile=szhzinfo_20180319.dmp logfile=szhzi ...

  7. python之ProcessPoolExecutor

    ProcessPoolExecutor使用上基本与ThreadPoolExecutor一致不过在windows上使用,有个问题需要注意.使用不当会出现如下错误 File "...\lib\m ...

  8. 请对比 Exception 和 Error,另外,运行时异常与一般异常有什么区别?

    error指的是不可预料的错误,可能会导致程序宕机:而exception指的是在程序运行中可以预见的异常,而异常分为检查异常与一般异常,检查异常需要在程序中显示捕获并处理,一般异常可以通过程序编码来进 ...

  9. JSONP--解决ajax跨域问题

    JSON和JSONP JSONP和JSON好像啊,他们之间有什么联系吗? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.对于JSON大家应该是很了解了吧 ...

  10. python核心编程2 第十五章 练习

    15-1.识别下列字符串 :“bat ”.“bit ”.“but ”.“hat ”.“hit” 或 “hut ” import re from random import choice strtupl ...