3

我玩了很多新的统一初始化{}像这样:

vector<int> x = {1,2,3,4};
map<int,string> getMap() {
    return { {1,"hello"}, {2,"you"} };
}

毫无疑问,这种初始化可能会改变我们对 C++ 的编程。但我想知道在Herb Sutter 常见问题解答中阅读Alfonses 的问题时是否错过了一些神奇的可能性

Alfonse:统一初始化(当可以推断出正在构造的类型时使用 {} 调用构造函数)有可能从根本上减少创建 C++ 类型所需的类型数量。就像 lambdas 一样,它会改变人们编写 C++ 代码的方式。[...]

有人可以给我一个例子来说明Alfonse在这里的设想吗?

4

2 回答 2

6

我想他的意思是

std::vector<int> x{1, 2, 3, 4};
std::map<int, std::string> y{{1, "hello"}, {2, "you"}};

打字明显少于

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");
于 2011-09-16T14:56:03.080 回答
1

为什么你不认为这是一个简单的错误?也就是说,当他的意思是“创建 C++ 对象”时,他写了“创建 C++ 类型”。奇怪的是,人们不会立即想到,“哦,他的意思是‘对象’,但写错了。”

于 2011-09-23T10:57:10.550 回答