构造函数中的初始化列表

use*_*451 5 c++ constructor initialization-list

我听说在构造函数中使用初始化列表的优点是不会有类型对象的额外副本.但是对于T类构造函数中的以下代码,它意味着什么?如果我评论分配并使用初始化列表会有什么区别?

#include <iostream>
using std::cout;
using std::endl;
using std::ostream;

class X {

public:

    X(float f_x = 0, float f_y = 0):x(f_x), y(f_y) {}


    ~X() {}

    X(const X& obj):x(obj.x), y(obj.y) {}

    friend ostream& operator << (ostream &os, X &obj);

private:
    float x;
    float y;
};

ostream& operator << (ostream &os, X &obj)
{ os << "x = " << obj.x << " y = " << obj.y; return os;}

class T {

public:

    T(X &obj) : x(obj) { /* x = obj */ }

    ~T() { }

    friend ostream& operator << (ostream &os, T &obj);

private:

    X x;

};

ostream& operator << (ostream &os, T &obj)
{ os << obj.x; return os; }

int main()
{
    X temp_x(4.6f, 6.5f);

    T t(temp_x);

    cout << t << endl;

}
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 6

这正是你已经说过的.如果不使用初始化列表,则首先调用默认构造函数,然后调用赋值运算符.

在你的例子中,这是相对良性的(我认为编译器甚至可以优化它).但在其他情况下,根本无法避免初始化列表.想象一下,如果X没有公共任务运营商.


Alo*_*ave 5

如果您使用Assignment,则:
x将首先默认构建
然后分配obj.

成本是,默认构造+分配


如果您使用成员初始化列表,则:
x将构造并初始化obj.

费用是,仅限建筑