初始化列表的好处 [英] Benefits of Initialization lists

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

问题描述

我知道使用初始化列表的好处是,它们在初始化不是内置的类成员时提供了效率。例如,

Of what I know of benefits of using initialization list is that they provide efficiency when initializing class members which are not build-in. For example,

Fred :: Fred():x_(无论){}

优于

Fred :: Fred(){x_ = whatever; }

如果x是自定义类的对象。除此之外,这种风格甚至与内置类型为了一致性使用。

if x is an object of a custom class. Other than that, this style is used even with built-in types for the sake of consistency.

这样做最常见的好处是提高性能。如果表达式是与成员变量x_相同的类型,则无论何种表达式的结果直接在x_中构造 - 编译器不会创建对象的单独副本。

The most common benefit of doing this is improved performance. If the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ — the compiler does not make a separate copy of the object.

对于另一种风格,表达式any会创建一个单独的临时对象,并将该临时对象传递给x_对象的赋值运算符。然后这个临时对象被破坏在。这是低效率的。

With the other style, the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the x_ object's assignment operator. Then that temporary object is destructed at the ;. That's inefficient.

问题

在使用初始化列表的下面的示例中有任何效率增益。
我认为没有收益。第一个版本调用字符串的复制构造函数和其他调用字符串的赋值运算符(没有任何临时创建的)。它正确吗?

Question
Is there any efficiency gain in the following example with using initialization list. I think there is no gain. The first version calls string's copy constructor and the other calls string's assignment operator (there isn't any temporary thats created). It that correct?

class MyClass
{
public:
    MyClass(string n):name(n) { }
private:
    string name;
};

class MyClass
{
public:
    MyClass(string n)
    {
	    name=n;
    }
private:
    string name;
};


推荐答案

第二个版本是调用字符串的默认ctor,复制赋值运算符 - 与第一个相比,直接调用c的copy-ctor(例如,根据字符串的实现,可能存在一些微小结构的无用的分配 - 然后释放) 。为什么不只是总是使用正确的方式? - )

The second version is calling string's default ctor and then string's copy-assignment operator -- there could definitely be (minor) efficiency losses compared to the first one, which directly calls c's copy-ctor (e.g., depending on string's implementation, there might be useless allocation-then-release of some tiny structure). Why not just always use the right way?-)

这篇关于初始化列表的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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