直接初始化与原语的复制初始化 [英] Direct Initialization vs Copy Initialization for Primitives

查看:84
本文介绍了直接初始化与原语的复制初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化诸如 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.

在模板内部,代码可能是

Inside a template, the code could be

for (T i(0); i < 5; ++i) {
    cout << i << endl;
}

并以这种方式在任何地方编写都会使编码风格保持一致。

and writing it that way everywhere would make the coding style consistent.

这篇关于直接初始化与原语的复制初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆