简体   繁体   English

何时调用复制构造函数或赋值构造函数?

[英]When copy constructor or assignment constructor is called?

Triny the quiz from web and see this code. Triny the quiz from web and see this code。 The result prints is 02结果打印为 02

Which means default copy constructor is used for list initialization while assignment constructor is used for vector.这意味着默认复制构造函数用于列表初始化,而赋值构造函数用于向量。 Why?为什么?

#include <algorithm>
#include <iostream>
#include <list>
#include <vector>

class Int
{
public:
    Int(int i = 0) : m_i(i) { }

public:
    bool operator<(const Int& a) const { return this->m_i < a.m_i; }

    Int& operator=(const Int &a)
    {
        this->m_i = a.m_i;
        ++m_assignments;
        return *this;
    }

    static int get_assignments() { return m_assignments; }

private:
    int m_i;
    static int m_assignments;
};

int Int::m_assignments = 0;

int main()
{
    std::list<Int> l({ Int(3), Int(1) });
    l.sort();
    std::cout << (Int::get_assignments() > 0 ? 1 : 0);

    std::vector<Int> v({ Int(2), Int() });
    std::sort(v.begin(), v.end());
    std::cout << (Int::get_assignments() > 0 ? 2 : 0) << std::endl;

    return 0;
}

Which means default copy constructor is used for list initialization while assignment constructor is used for vector这意味着默认复制构造函数用于列表初始化,而赋值构造函数用于向量

If you remove the std::sort(v.begin(), v.end());如果删除std::sort(v.begin(), v.end()); instruction the program prints 00 .指令程序打印00 The assignment operator is used just for sorting.赋值运算符仅用于排序。

NOTE : the list can be sorted simply by modifying pointers (so l.sort() doesn't require operator= ).注意:列表可以简单地通过修改指针进行排序(因此l.sort()不需要operator= )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM