标签:
1 namespace std{ 2 template<typename T> 3 void swap(T& a, T& b) //std::swap的典型实现 4 { 5 T temp(a); //一次拷贝,两次赋值 6 a = b; 7 b = temp; 8 } 9 }
void T::swap(T& t) noexcept;
1 void swap(T& a, T& b) noexcept 2 { 3 a.swap(b); 4 }
1 #include <iostream> 2 #include <string> 3 class ClassTest{ 4 public: 5 friend std::ostream& operator<<(std::ostream &os, const ClassTest& s); 6 friend void swap(ClassTest &a, ClassTest &b) noexcept; 7 ClassTest(std::string s = "abc") :str(new std::string(s)){} //默认构造函数 8 ClassTest(const ClassTest &ct) :str(new std::string(*ct.str)){} //拷贝构造函数 9 ClassTest &operator=(const ClassTest &ct) //拷贝赋值函数 10 { 11 str = new std::string(*ct.str); 12 return *this; 13 } 14 ~ClassTest() //析构函数 15 { 16 delete str; 17 } 18 void swap(ClassTest &t) noexcept 19 { 20 using std::swap; 21 swap(str,t.str); //交换指针,而不是string数据 22 } 23 private: 24 std::string *str; //一个指针资源 25 }; 26 std::ostream& operator<<(std::ostream &os,const ClassTest& s) 27 { 28 os << *s.str; 29 return os; 30 } 31 void swap(ClassTest &a, ClassTest &b) noexcept 32 { 33 a.swap(b); 34 } 35 int main(int argc, char const *argv[]) 36 { 37 ClassTest ct1("ct1"); 38 ClassTest ct2("ct2"); 39 std::cout << ct1 << std::endl; 40 std::cout << ct2 << std::endl; 41 swap(ct1, ct2); 42 std::cout << ct1 << std::endl; 43 std::cout << ct2 << std::endl; 44 return 0; 45 }
1 void swap(ClassTest &t) noexcept 2 { 3 using std::swap; 4 swap(str, t.str); //交换指针,而不是string数据 5 }
1 void swap(ClassTest &a, ClassTest &b) noexcept 2 { 3 using std::swap; 4 //swap交换操作 5 }
1 #include <iostream> 2 #include <string> 3 class ClassTest{ 4 public: 5 friend std::ostream& operator<<(std::ostream &os, const ClassTest& s); 6 friend void swap(ClassTest &a, ClassTest &b) noexcept; 7 ClassTest(std::string s = "abc") :str(new std::string(s)){} //默认构造函数 8 ClassTest(const ClassTest &ct) :str(new std::string(*ct.str)){} //拷贝构造函数 9 ClassTest &operator=(const ClassTest &ct) //拷贝赋值函数 10 { 11 str = new std::string(*ct.str); 12 return *this; 13 } 14 ~ClassTest() //析构函数 15 { 16 delete str; 17 } 18 private: 19 std::string *str; //一个指针资源 20 }; 21 std::ostream& operator<<(std::ostream &os, const ClassTest& s) 22 { 23 os << *s.str; 24 return os; 25 } 26 void swap(ClassTest &a, ClassTest &b) noexcept 27 { 28 using std::swap; 29 swap(a.str,b.str); //交换指针,而不是string数据 30 } 31 int main(int argc, char const *argv[]) 32 { 33 ClassTest ct1("ct1"); 34 ClassTest ct2("ct2"); 35 std::cout << ct1 << std::endl; 36 std::cout << ct2 << std::endl; 37 swap(ct1, ct2); 38 std::cout << ct1 << std::endl; 39 std::cout << ct2 << std::endl; 40 return 0; 41 }
本文链接:【原创】C++之swap(1) http://www.cnblogs.com/cposture/p/4939971.html
标签:
原文地址:http://www.cnblogs.com/cposture/p/4939971.html