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

When copy constructor or assignment constructor is called?

本文关键字:构造函数 赋值 调用 复制      更新时间:2023-10-16

>从网络上进行测验并查看此代码。打印结果为 02

这意味着默认复制构造函数用于列表初始化,而赋值构造函数用于向量。为什么?

#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;
}

这意味着默认复制构造函数用于列表初始化,而赋值构造函数用于向量

如果删除std::sort(v.begin(), v.end());指令,程序将打印00 。赋值运算符仅用于排序。

注意:列表可以通过修改指针简单地进行排序(因此l.sort()不需要operator=)。