swap函數執行會調用容器內數據類型的,拷貝構造和賦值函數調用
對自定義類型使用STL algorithm中的swap函數,會調用自定義的類型的拷貝構造函數一次,賦值函數兩次;自定義類型中沒有定義那麼就會使用默認的拷貝構造函數和賦值函數。 如果是容器,那麼會遍歷容易進行賦值。
swap函數可用於清空vector和string類型容器分配的內存空間
對於vector, string, basic_string容器clear後不會釋放佔有的內存空間capacity,而只是減少了內存上的數據元素size。
如果要對vector,string進行清空不再使用的內存,那麼需要調用swap來清理掉。其它的stl容器調用clear時候是會清空內存空間的。
STL中的swap源碼:
/ TEMPLATE FUNCTION swap (from <algorithm>)
template<class _Ty> inline
void swap(_Ty& _Left, _Ty& _Right)
{ // exchange values stored at _Left and _Right
_Ty _Tmp = _Move(_Left);
_Left = _Move(_Right);
_Right = _Move(_Tmp);
}
測試例子
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
struct tagStudent
{
int m_nID;
int m_nScore;
tagStudent& operator =(const tagStudent &b)
{
this->m_nID = b.m_nID;
this->m_nScore = b.m_nScore;
return *this;
}
tagStudent( const tagStudent &b)
{
this->m_nID = b.m_nID;
this->m_nScore = b.m_nScore;
}
tagStudent( int nID, int nScore )
{
this->m_nID = nID;
this->m_nScore = nScore;
}
};
void main()
{
tagStudent AStudent(2, 20);
tagStudent BStudent(3, 80);
// 在tagStudent中的拷貝構造和賦值函數中打斷點會發現,拷貝構造調用了一次,賦值函數調用了兩次
std::swap( AStudent, BStudent);
int x = 10;
//vector<int> myContainer(10000, x);
string myContainer(10000,'\0');
//這裏打印僅僅是元素的個數不是內存大小
cout << "myContainer size :" << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl;
myContainer.clear();;
cout << "after clear size :" << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl;
//swap交換函數釋放內存:vector<T>().swap(X);
//T:int ; myvertor代表X
//vector<int>().swap(myContainer);
string().swap(myContainer);
//兩個輸出僅用來表示swap前後的變化
cout << "after swap size :" << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl;
// 並不是所有的STL容器的clear成員函數的行爲都和vector一樣。事實上,其他容器的clear成員函數都會釋放其內存。
}
運行結果如下: