标准与显式自动推导变量声明

Standard vs explicit auto-deduced variable declaration

本文关键字:变量 声明 标准      更新时间:2023-10-16

考虑这两个等效变量声明:

int foo{5};
auto bar = int{5};

使用后一种语法有什么好处吗?

首选第一种语法,因为第一种情况下没有额外的副本,但在第二种情况下,我们创建了一个临时对象,然后将该对象复制到原始变量。但只有在禁用复制的情况下

使用禁用的副本

int foo{5}; // No temporary object
auto bar = int{5}; // Created temporary object and then it is copied in bar

启用复制 elison

int foo{5}; // No difference with the second line
auto bar = int{5}; // No difference with the first line

在这个例子中没有。您需要使用具有复杂类型的新语法。即,在带有迭代器或模板定义的内部 for 循环。
比较:

vector<int> v = {1, 2, 3};
for (auto x : v) std::cout << x << ' ' << std::endl;

和:

vector<int> v = {1, 2, 3};
for (std::vector<int>::iterator x = v.begin(); x != v.end(); ++x) std::cout << x << ' ' << std::endl;