标准与显式自动推导变量声明
Standard vs explicit auto-deduced variable declaration
考虑这两个等效变量声明:
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;
相关文章:
- 在将变量声明为引用时,堆在释放后使用
- 静态变量声明和定义
- 在变量声明中使用 for 循环
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- C++ 类型类的变量声明不命名类型?
- 将本地 OpenCV Mat 变量声明为静态以防止重新分配
- std::enable_if 更改成员 *变量* 声明/类型
- 在C++中,变量声明左侧的大括号是什么意思?
- 将变量声明为全局变量,然后声明为局部变量 -Shadowing-
- 命名空间内C++变量声明
- 将静态全局变量声明为内联有什么意义吗?
- 如何将一个变量声明为另一个变量的值
- 如何将迭代器变量声明为私有成员变量
- 没有变量声明为函数,但错误:二进制表达式的操作数无效
- 有没有人有书面证据来保证函数中参数的定义方式与普通变量声明相同?
- ClangTool 如何获取变量声明中模板参数的位置?
- 标准与显式自动推导变量声明
- C 静态变量声明怪异链接器错误
- 如何为数组成员变量声明 getter/setter
- 可视C++变量声明