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)
{
_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);
std::swap( AStudent, BStudent);
int x = 10;
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;
string().swap(myContainer);
cout << "after swap size :" << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl;
}
运行结果如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)