










在C++17中,如果你不显示的声明构造函数和赋值函数时,编译器会自动生成6个核心特殊成员函数:
1. 默认构造函数: 无参构造
2. 析构函数: 清理资源
3. 拷贝构造函数: 用同类的对象来初始化新的对象
4. 拷贝赋值运算符: 对象之间赋值
5. 移动构造函数(C++11/17 新增): 转移对象资源
6. 移动赋值运算符(C++11/17 新增): 转移赋值
我们来看一个例子, 我们新建一个空类Person
#include <iostream> using namespace std; //空类,没有一行代码 class Person { // 编译器会自动生成上面6个函数 }
编译器为上面Person这个空类,大概会生成以下6个成员函数
class Person { public: // 1. 默认构造函数 Person() = default; //2. 析构函数 ~Person() = default; //3. 拷贝构造函数 Person(const Person&) = default; //4. 移动构造函数 Person(Person&&) = default; //5. 拷贝运算符 Person& operator= (const Person&) = default; //6. 移动运算符 Person& operator= (Person&&) = default; }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。