copy构造函数和=运算符之间有什么区别

Cry*_*ake 0 c++

我写了一个简单的代码,我的问题是:为什么item_base只调用constrcut函数?应该调用item_base"copy construct function"吗?我观察到当我创建item_base2时,它调用"copy construct function",但是item_base不调用"copy"构造函数".有什么区别?

class Item_base {
    public:
        Item_base();
        Item_base(int);
        Item_base(const Item_base &base);
        void operator=(const Item_base &item);
        virtual ~Item_base();
};

Item_base::Item_base()
{
    cout << "construct function" << endl;
}

Item_base::Item_base(int a)
{
    cout << "arg construct function" << endl;
}
Item_base::Item_base(const Item_base &base)
{
    cout << "copy function" << endl;
}

void Item_base::operator=(const Item_base &item)
{
    cout << "= operator" << endl;
}

Item_base::~Item_base()
{
}


int main()
{
    //cout << "Hello world!" << endl;
    Item_base item_base = Item_base(1);//construct function
    Item_base item_base2 = item_base;//copy construct  function
    Item_base item_base3;
    item_base3 = item_base2;// =operator function
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*sop 5

它被称为"复制省略"或"复制构造函数省略".C++标准允许实现省略某些副本.从临时对象Item_base(1)到变量的item_base副本就是这样一个副本.

这同样适用于C++ 11中的移动.

因此,当您定义时item_base,在您的实现中,它只是使用参数构造1,而不是构造临时构造然后复制.所有有价值的编译器都实现了copy elision,尽管如果你用编译器选项禁用它,你会看到两个构造函数在这里调用.

定义时item_base2,item_base必须复制,因为没有其他方法可用于初始化item_base2.

在定义时,item_base3它构造时没有参数.

分配给item_base3它时已经存在,因此当然没有构造.调用赋值运算符.