为什么使用=来初始化C ++中的原始类型? [英] Why use = to initialise a primitive type in C++?

查看:99
本文介绍了为什么使用=来初始化C ++中的原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我工作的地方,人们通常认为对象最好使用C ++风格构造(带括号)初始化,而原始类型应该使用=运算符初始化:

Where I work, people mostly think that objects are best initialised using C++-style construction (with parentheses), whereas primitive types should be initialised with the = operator:

std::string strFoo( "Foo" );
int nBar = 5;

没人能解释为什么他们喜欢这种方式。我可以看到, std :: string =Foo; 将是低效的,因为它将涉及一个额外的副本,但是错误的只是废除 = 运算符,并使用括号到处?

Nobody seems to be able to explain why they prefer things this way, though. I can see that std::string = "Foo"; would be inefficient because it would involve an extra copy, but what's wrong with just banishing the = operator altogether and using parentheses everywhere?

这是一个常见的约定吗?

Is it a common convention? What's the thinking behind it?

推荐答案

除非你已经证明它对性能很重要,否则我不担心在您的示例中使用赋值运算符( std :: string foo =Foo; )进行额外复制。如果这个副本甚至存在,一旦你看到优化的代码,我相信,实际上会调用相应的参数化构造函数。

Unless you've proven that it matters with respect to performance, I wouldn't worry about an extra copy using the assignment operator in your example (std::string foo = "Foo";). I'd be pretty surprised if that copy even exists once you look at the optimized code, I believe that will actually call the appropriate parameterized constructor.

在回答你的问题,是的,我会说这是一个相当普遍的约定。通常,人们使用赋值来初始化内置类型,并没有一个令人信服的理由来改变传统。可读性和习惯是这个约定的完美有效的原因,因为它对最终代码的影响很小。

In answer to your question, yes, I'd say that it's a pretty common convention. Classically, people have used assignment to initialize built-in types, and there isn't a compelling reason to change the tradition. Readability and habit are perfectly valid reasons for this convention given how little impact it has on the ultimate code.

这篇关于为什么使用=来初始化C ++中的原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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