Direct Initialization vs Copy Initialization for Primitives(基元的直接初始化与复制初始化)
问题描述
在初始化 int 或指针等原始类型时,可以使用 copy-initialization 或 direct-initialization.
When initializing primitive types like int or pointers one can use either copy-initialization or direct-initialization.
int a = 10;
int b(10);
虽然后一种方式更适合带有构造函数的对象,但我没有看到人们将它用于原语.我知道使用 '=' 运算符有点更自然"(尤其是对于数字而言),但是有没有人在现实生活中编写代码:
Although the latter way is preffered for objects with constructors, I don't see people using it for primitives. I understand that it is kind of "more natural" (especially for numbers) to use the '=' operator but is there anybody writing things like in real-life code:
for (int i(0); i < 5; ++i) {
cout << i << endl;
}
谢谢.
这个问题询问的是编码风格和最佳实践,而不是技术实现.
The question asks about coding styles and best practices rather than technical implementation.
推荐答案
有些人这样做是为了保持一致.
Some people do this to be consistent.
在模板中,代码可以是
for (T i(0); i < 5; ++i) {
cout << i << endl;
}
在任何地方都这样写可以使编码风格保持一致.
and writing it that way everywhere would make the coding style consistent.
这篇关于基元的直接初始化与复制初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基元的直接初始化与复制初始化
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
