STL中的swap函数 |
您所在的位置:网站首页 › swap函数的使用 › STL中的swap函数 |
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 ) template 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 #include #include #include #include #include #include #include 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 myContainer(10000, x); string myContainer(10000,'\0'); //这里打印仅仅是元素的个数不是内存大小 cout |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |