Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Last active August 18, 2023 11:45
Show Gist options
  • Save ZJUGuoShuai/a39f64b2fca805f8ca57eba5b2c1fc57 to your computer and use it in GitHub Desktop.
Save ZJUGuoShuai/a39f64b2fca805f8ca57eba5b2c1fc57 to your computer and use it in GitHub Desktop.
C++ STL 中的 std::swap 通常是如何实现的?

C++ STL 中的 std::swap 通常是如何实现的?

C++11 之前,只能使用拷贝构造和拷贝赋值:

template <typename T>
void swap(T& a, T& b) {
  T t = a;
  b = a;
  b = t;
}

C++11 之后,如果类型 T 实现了移动语义,则可以避免拷贝;若未实现移动语义,则与之前相同:

template <typename T>
void swap(T& a, T& b) {
  T t = std::move(a);
  a = std::move(b);
  b = std::move(t);
}

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment