Skip to content

Commit

Permalink
[cpp] 明确 copy-and-swap 中交换函数是自定义的
Browse files Browse the repository at this point in the history
  • Loading branch information
FeignClaims authored Mar 19, 2024
1 parent 0d3e64e commit 43e52cb
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions faq/copy_assignment_define/main.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,23 @@ copy-and-swap: 拷贝赋值函数的简单实现

.. code-block:: cpp
:linenos:
:caption: 拷贝赋值函数
Widget& operator=(Widget const& other) {
Widget temp(other); // 拷贝 other 到 temp
swap(*this, temp); // 交换 temp 和 *this 的内容; 该函数怎么来的见下文
return *this;
} // temp 的析构函数将会对交换来的 *this 内容完成必要的清理
.. code-block:: cpp
:linenos:
:caption: :cpp:`swap` 函数
// 如果是 C++11 及以后, 加上 noexcept 表示不会抛出异常 ↓
friend void swap(Widget& lhs, Widget& rhs) noexcept {
/* 交换 lhs 和 rhs 的所有成员 */
}
.. admonition:: 相关核心准则
:class: coreguidelines

Expand Down

0 comments on commit 43e52cb

Please sign in to comment.