调用复制构造函数或赋值构造函数时
When copy constructor or assignment constructor is called?
>从网络上进行测验并查看此代码。打印结果为 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=
)。
相关文章:
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 初始值设定项列表与构造函数赋值与变量定义
- std::vector::emplace() 真的在面对抛出移动构造函数/赋值运算符时提供了强大的异常保证吗?
- 创建一个类并在C++中使用构造函数(赋值)
- 如何为具有自引用指针的类实现复制构造函数/赋值运算符
- 使typedef的构造函数/赋值运算符成为友元函数
- 复制构造函数+赋值运算符
- C++ 矢量从构造函数赋值对象,无需临时
- 具有std::原子成员变量的类的复制构造函数/赋值运算符出错
- 初始化对象时复制构造函数/赋值运算符混淆
- 默认情况下是默认的构造函数/赋值noexcept/constexpr
- 模板是否应该为不同类型的参数制作非 Rvalue 引用构造函数/赋值
- 为什么 std 类型不提供来自分配器不同源的转换构造函数/赋值
- 是否为派生类生成的移动构造函数/赋值运算符
- 复制构造函数/赋值运算符
- C++复制构造函数/赋值运算符错误
- 正在获取要使用的移动构造函数/赋值运算符
- 影响正确性的move构造函数/赋值操作符示例