随着移动构造器的出现,它现在是六巨头。在这里学习并了解所有细节,您将获得类样板硕士学位。
#include <list>
class A {};
class B {};
class C{
std::list<A> a;
std::list<B> b;
public:
typedef std::list<A>::size_type size_type;
explicit C(size_type sz =0);
virtual ~C();
C(const C& c);
// Specialize external swap. Necessary for assignment operator below,
// and for ADL (argument-dependant lookup).
friend void swap(C& first, C& second);
// Assignment-operator. Note that the argument "other" is passed by value.
// This is the copy-and-swap idiom (best practice).
C& operator=(C other); // NOTE WELL. Passed by value
// move-constructor - construct-and-swap idiom (best practice)
C(C&& other);
};
C::C(size_type sz) : a(sz), b(sz) {}
C::~C(){}
C::C(const C& c) :a(c.a), b(c.b){}
void swap(C& first, C& second) {
// enable ADL (best practice)
using std::swap;
swap(first.a, second.a);
swap(first.b, second.b);
}
// Assignment-operator. Note that the argument "other" is passed by value.
// This is the copy-and-swap idiom (best practice).
C& C::operator=(C other) {
swap(*this, other); // Uses specialized swap above.
return *this;
}
// move-constructor - construct-and-swap idiom (best practice)
C::C(C&& other): a(0) , b(0) {
swap(*this, other);
}