tow*_*owi 3 initialization initializer-list uniform-initialization c++11
我已经打了很多新的统一初始化用{}.像这样:
vector<int> x = {1,2,3,4};
map<int,string> getMap() {
return { {1,"hello"}, {2,"you"} };
}
Run Code Online (Sandbox Code Playgroud)
毫无疑问,这种初始化可能会改变我们的程序C++.但是我想知道在Herb Sutter常见问题解答中阅读Alfonses的问题时我是否错过了一些神奇的可能性.
Alfonse:统一初始化(在推导构造的类型时使用{}调用构造函数)有可能从根本上减少创建C++类型所需的键入数量.就像lambdas一样,它会改变人们编写C++代码的方式.[...]
有人能给我一个Alfonse在这里设想的例子吗?
我认为他的意思是
std::vector<int> x{1, 2, 3, 4};
std::map<int, std::string> y{{1, "hello"}, {2, "you"}};
Run Code Online (Sandbox Code Playgroud)
打字明显少于
std::vector<int> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
x.push_back(4);
std::map<int, std::string> y;
y.emplace(1, "hello");
y.emplace(2, "you");
Run Code Online (Sandbox Code Playgroud)