类的swap
#include <vector>
#include <memory>
class WidgetImpl
{
public:
WidgetImpl() = default;
~WidgetImpl() = default;
private:
int m_a, m_b, m_c;
std::vector<double> m_v;
};
class Widget
{
public:
Widget() : m_Impl(new WidgetImpl){}
~Widget()= default;
Widget & operator=(const Widget & rhs)
{
*m_Impl = *(rhs.m_Impl);
return *this;
}
void swap(Widget &other) {
std::swap(m_Impl, other.m_Impl);
}
private:
std::shared_ptr<WidgetImpl> m_Impl;
};
namespace std {
template<>
void swap<Widget>(Widget &a, Widget &b)
{
a.swap(b);
}
}
using namespace std;
int main() {
Widget aw;
Widget bw;
swap(aw, bw);
return 0;
}
class templates的swap
#include <vector>
#include <memory>
namespace WidgetStuff
{
template<typename T>
class WidgetImpl
{
public:
WidgetImpl() = default;
~WidgetImpl() = default;
private:
T m_a, m_b, m_c;
std::vector<T> m_v;
};
template<typename T>
class Widget
{
public:
Widget() : m_Impl(new WidgetImpl<T>) {}
~Widget() = default;
Widget & operator=(const Widget & rhs)
{
*m_Impl = *(rhs.m_Impl);
return *this;
}
void swap(Widget &other) {
std::swap(m_Impl, other.m_Impl);
}
private:
std::shared_ptr<WidgetImpl<T> > m_Impl;
};
template<typename T>
void swap(Widget<T> &a, Widget<T> &b)
{
a.swap(b);
}
}
#if 0
namespace std {
template<typename T>
void swap(WidgetStuff::Widget<T> &a, WidgetStuff::Widget<T> &b)
{
a.swap(b);
}
}
#endif
using namespace std;
int main() {
WidgetStuff::Widget<int> aw;
WidgetStuff::Widget<int> bw;
swap(aw, bw);
int a = 2, b = 3;
swap(a,b);
return 0;
}