swap は C++ では重要な基本操作の一つとして扱われます。
実際、例外を投げないことと、O(1)であることから、使い所が多いです。
メンバ関数としての swap() と共に、グローバル変数としての swap() も定義します。
template <typename T>
class myvector
{
...
public:
/**
* @brief Exchanges the contents of the container with those of other.
* Does not invoke any move, copy, or swap operations on individual
* elements.
* @param[in,out] other: Container to exchange the contents with.
*/
void swap(self_type& other) noexcept
{
std::swap(heap_, other.heap_);
std::swap(size_, other.size_);
std::swap(capacity_, other.capacity_);
}
...
};
/**
* @brief Swaps the contents of lhs and rhs. Calls lhs.swap(rhs).
* @param[in,out] lhs: Containers whose contents to swap.
* @param[in,out] rhs: Containers whose contents to swap.
* @tparam T: The type of the myvector elements.
*/
template <class T>
void swap(myvector<T>& lhs, myvector<T>& rhs) noexcept
{
lhs.swap(rhs);
}
swap() の中身は、3つのメンバ変数すべての交換する処理となります。領域確保等は無いので、例外無しとすることができます。
全ソースコード: https://github.com/suomesta/myvector/tree/master/031
0 件のコメント:
コメントを投稿