🐭 类的特殊成员函数
我们可以很简单的来设计一个类,但是编译器会暗地里帮我们按需生成一些特殊的类成员函数,特殊类成员函数可以分为,默认构造函数,析构函数,拷贝操作函数,移动操作函数四个类别:
- 默认构造函数
- 析构函数
- 拷贝构造函数
- 拷贝赋值操作符
- 移动构造函数
- 移动赋值操作符
代码示例 :
#include <iostream>class X {};class Y {public:// 1. default constructorY() = default;// 2. destructor~Y() = default;// 3. copy constructorY(const Y &rhs) { std::cout << "copy constructor\n"; }// 4. copy assignmentY &operator=(const Y &rhs) {if (this != &rhs) {std::cout << "copy assignment\n";}return *this;}// 5. move constructorY(Y &&rhs) { std::cout << "move constructor\n"; }// 6. move assignmentY &operator=(Y &&rhs) {if (this != &rhs) {std::cout << "move assignment\n";}return *this;}};int main() {// 1. call default constructorX x1{};Y y1{};// 2. call copy constructorX x2{x1};X x3 = x1;Y y2{y1}; // copy constructorY y3 = y1; // copy constructor// 3. call copy assignmentX x4{};x4 = x1;Y y4{};y4 = y1; // copy assignment// 4. call move constructor// use static_cast / std::forward / std::move to prevents copy elision// otherwise, will directly call the constructorsX x5 = std::move(X{});Y y5 = std::move(Y{}); // move constructor// x6, y6 apply the copy elision (C++17)// calls the default constructor directly, no copies, no movesX x6 = X{};Y y6 = Y{};// 5. call move assignmentX x7{};x7 = X{};Y y7{};y7 = Y{}; // move assignmentreturn 0;}
:::tips
- 注意 C++17 引入的拷贝消除机制 (copy elision)
- 对比 X 与 Y 两个类,编译器确实在背后做了一些手脚
-
🐂 附加说明
这 6 个成员函数之所以特殊,是因为它们可能会被编译器暗地里按需生成,生成规则比较复杂,下面分开来介绍,一些废弃了的规则不再介绍。
属于用户定制的特殊成员函数包括: 手动声明的特殊成员函数
- 手动定义的特殊成员函数
- 手动声明为 “= default” 的特殊成员函数
- 手动声明为 “= delete” 的特殊成员函数
按成员拷贝与按成员移动:
按成员拷贝(包括拷贝与拷贝赋值),是指按照类的非静态数据成员一个一个的去调用其拷贝构造函数或者拷贝赋值操作符。
按成员移动(包括移动与移动赋值),是指按照类的非静态数据成员一个一个的去调用其移动构造函数或者移动赋值操作符,不支持移动的成员,则退化为将其按成员拷贝。
🐯 默认构造函数与析构函数
默认构造函数:
当用户没有定制任何形式构造函数时,编译器会按需生成默认构造函数,逐成员调用成员的默认构造函数。
析构函数:
当用户没有定制析构函数时,编译器会生成异常安全的析构函数,当其基类有虚析构函数时,生成的析构函数也是虚析构函数。
代码示例 :
#include <iostream>#include <string>#include <string_view>class Job {public:// if user defined a constructor, no compiler default constructor will be generatedJob(std::string_view sv) : name_{sv} {}// but we can use '= default' to take the compiler default constructor back// Job() = default;private:std::string name_;};struct B {// user defined virtual destructorvirtual ~B() noexcept = default;};struct D : B {// the compiler will generate a virtual, noexcept destructor for class D};int main() {// Job j; // not compiles, since no default constructorD d;std::cout << std::boolalpha;std::cout << std::has_virtual_destructor_v<D> << '\n'; // truestd::cout << noexcept(std::declval<D>().~D()) << '\n'; // truereturn 0;}
:::tips
假定一个类的类名称为 X:
这里说到的任何形式的构造函数,指的是函数名称为 X 的所有成员函数,包括拷贝构造函数与移动构造函数
这里说到的析构函数,指的是函数名称为 ~X 的成员函数
:::
🐰 拷贝操作函数与移动操作函数
类的拷贝操作:
类的拷贝操作包括拷贝构造与拷贝赋值,它们之间是相互独立的,用户定制其中一个,不会阻止编译器生成另外一个。
类的移动操作:
类的移动操作包括移动构造与移动赋值,它们之间是互斥的,用户定制其中一个,会阻止编译器生成另外一个。另外,用户定制析构函数也会阻止编译器生成类的移动操作。
类的拷贝操作与移动操作:
类的拷贝操作与移动操作它们之间也是互斥的,用户定制其中一类,会阻止编译器生成另外一类。
:::tips
理解什么是 ‘Rule of Three’, ‘Rule of Five’ 与 ‘Rule of Zero’
- ‘Rule of Zero’: 不要声明 2~6 这五个特殊成员函数,如果需要其中的一个,声明其它的为 ‘=default’
- 对于 1 号默认构造函数,也没必要定义,建议 explicit 地定义一个合适构造函数
:::
🐲 类的拷贝操作
类的拷贝操作代码示例: ```cppinclude
struct X { // copy constructor X(const X &) = delete; };
struct Y { // copy assignment operator Y &operator=(const Y &) = delete; };
int main() { std::cout << std::boolalpha;
// 1. delete the copy constructor, does not impact the copy assignment operator
std::cout << std::is_copy_constructible_v
// 2. delete the copy assignment operator, does not impact the copy constructor
std::cout << std::is_copy_assignable_v
// Types without move operations
// but with a copy operations that accepts const T& arguments
// satisfy std::is_move_constructible / std::is_move_assignable
// 3. move operations fall back to copy operations
// std::is_copy_constructible_v
return 0; }
:::tips注意类移动操作可能会退化为相对应的拷贝操作:::<a name="XTlvF"></a>### 🐍 类的移动操作类的拷贝操作代码示例:```cpp#include <iostream>struct X {// move constructorX(X &&) = delete;};struct Y {// move assignment operatorY &operator=(Y &&) = delete;};struct Z {virtual ~Z() = default;};int main() {std::cout << std::boolalpha;// 1. delete the move constructor, impact the move assignment operatorstd::cout << std::is_move_constructible_v<X> << '\n'; // falsestd::cout << std::is_move_assignable_v<X> << '\n'; // false// 2. delete the move assignment operator, impact the move constructorstd::cout << std::is_move_assignable_v<Y> << '\n'; // falsestd::cout << std::is_move_constructible_v<Y> << '\n'; // false// 3. delete the move constructor, impact all the copy operationsstd::cout << std::is_copy_constructible_v<X> << '\n'; // falsestd::cout << std::is_copy_assignable_v<X> << '\n'; // false// 4. delete the move assignment operator, impact all the copy operationsstd::cout << std::is_copy_constructible_v<Y> << '\n'; // falsestd::cout << std::is_copy_assignable_v<Y> << '\n'; // false// 5. define the destructor// $ clang++ moveops.cpp -std=c++17 -Wdeprecated// a. implicit generate copy operations are deprecated// b. no move operations generated, and fall back to deprecated copy operationsZ z1;Z z2 = std::move(z1);return 0;}
:::tips 不要依赖一些过时了的语言与编译器特性 :::
🐎 总结
类特殊成员函数的编译器生成规则都比较好理解:
一旦用户定制了某个特殊成员函数,就暗示着编译器生成的那个没法满足要求。然后,编译器会进一步思考,那它生成的其他特殊成员函数是不是也没法满足要求呢?如果是那就干脆不要生成。在编译器那里,正确性永远是最重要的,编译器不会画蛇添足,过度优化。
