隐式赋值比显式赋值的优势 [英] Advantage of implicit assignment over explicit

查看:149
本文介绍了隐式赋值比显式赋值的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

隐式赋值比显式赋值有什么优势?
考虑下面的示例:

What is the advantage of implicit assignment over explicit assignment?
Consider the below example:

class base
{
    int b;
public:
    base()
    {
        b = 0;
    }
    base(int x):b(x)
    {
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    class base bobj(44);

    return 0;
}



通常,我已经看到类中的变量是使用隐式赋值进行初始化的,即使对于上面显示的标准数据类型也是如此.
为什么会这样呢?

下面显示的显式分配也具有相同的作用:



Normally I have seen variables in class are initialized with implicit assignment even for the standard data types as shown above.
Why it is preferred so?

The explicit assignment shown below also does the same thing:

base(int x)
{
        b = x;
}



那么为什么隐式优先于显式呢?
base(int x):b(x)优于
的优点是什么 base(int x)
{
b = x;
}
?



Then why is implicit preferred over explicit?
What is the advantage of base(int x):b(x) over
base(int x)
{
b = x;
}
?

推荐答案

阅读此内容可能会对您有所帮助

我的构造函数应该使用初始化列表"还是分配"? [ ^ ]
Read this maybe it will help you

Should my constructors use "initialization lists" or "assignment"?[^]




我建议您阅读Scott Meyer的有效C ++"和更有效的C ++".除非您这样做,否则您不能称自己为C ++程序员.他探索了如何编写维护成本低,高质量的代码,并明确说明了上面的查询.

HTH.
Hi,

I recommend you read Scott Meyer''s "Effective C++" and "More Effective C++". You can''t call yourself a C++ programmer until you do. He explores how to write low maintenance, high quality code and definately dicusses your query above.

HTH.


对于普通的旧数据(如int)成员,生成的代码几乎相同.
当b不是普通的旧数据时,优点就来了.
在这种情况下,生成的代码将具有默认构造,后跟分配,而不是显式构造.因此,成员初始化可以减少代码量.
对于这种情况,我唯一可以给您的警告或建议是,您应注意确保成员初始化不会假定成员的构造顺序.
For plain old data (like int) members the generated code is nearly identical.
The advantage comes when b is not plain old data.
In that situation the generated code would have a default construction followed by an assignment instead of an explicit construction. So member initialisation results in less code.
The only warning or recommendation I can give you for that case is that you should take care to ensure that the member initialisation doesn''t assume a construction order for the members.


这篇关于隐式赋值比显式赋值的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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