From eb8b75eff1b16f0656c1e9e79cc81b237d01438b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=92=E6=95=85=E9=87=8C?= <3326284481@qq.com> Date: Thu, 29 Feb 2024 21:58:41 +0800 Subject: [PATCH] Modifies the description of self-assignment in the move assignment operator. --- ...move-constructors-and-move-assignment-operators-cpp.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/cpp/move-constructors-and-move-assignment-operators-cpp.md b/docs/cpp/move-constructors-and-move-assignment-operators-cpp.md index 9cbab78ea2..b00f547676 100644 --- a/docs/cpp/move-constructors-and-move-assignment-operators-cpp.md +++ b/docs/cpp/move-constructors-and-move-assignment-operators-cpp.md @@ -125,7 +125,7 @@ The following procedures describe how to write a move constructor and a move ass } ``` -1. In the move assignment operator, add a conditional statement that performs no operation if you try to assign the object to itself. +1. In the move assignment operator, we need to keep the self-assignment safe, and the simple way is to add a judgment directly. ```cpp if (this != &other) @@ -133,6 +133,12 @@ The following procedures describe how to write a move constructor and a move ass } ``` + There are many other ways, too, such as `copy-and-swap`. + + ```cpp + shared_ptr(_Right).swap(*this); + ``` + 1. In the conditional statement, free any resources (such as memory) from the object that is being assigned to. The following example frees the `_data` member from the object that is being assigned to: