有关remove&erase
问题出在STL中多remove算法上面,这货根本就没有把合适的元素删除!!NEVER!它做的事情类似于排序,把需要删除的位置的元素用其他对象替换掉,而且调用多就是operator=。
看代码:
#include <iostream> #include <vector> #include <algorithm> using namespace std; namespace{ class MyObject{ public: // Constructor MyObject(int data): m_data(data) { cout<< "Constructing!:" << data <<endl; } // Copy constructor MyObject( const MyObject &obj ): m_data(obj.m_data) { cout<< "Copying: " << m_data << endl; } // Assign operator const MyObject& operator=(const MyObject& obj) { m_data = obj.m_data; cout<< "Assigning: " << m_data << endl; return *this; } // Compare opertor bool operator==(const MyObject &obj) { if( m_data == obj.m_data ) return true; else return false; } // Destructor ~MyObject() { cout<< "Destructing: " << m_data << endl; } int m_data; }; } void removeEarseTestMain() { vector<MyObject> vec; vec.push_back(MyObject(1)); vec.push_back(MyObject(2)); vec.push_back(MyObject(3)); vec.push_back(MyObject(2)); vec.push_back(MyObject(4)); vec.push_back(MyObject(5)); cout<< "prepare finished! ===========================================" << endl; auto iter = remove(vec.begin(), vec.end(), 2); cout<< "remove finished! ===========================================" << endl; vec.erase(iter, vec.end()); cout<< "erase finished! ===========================================" << endl; }
结果:
Constructing!:1 Copying: 1 Destructing: 1 Constructing!:2 Copying: 2 Copying: 1 Destructing: 1 Destructing: 2 Constructing!:3 Copying: 3 Copying: 1 Copying: 2 Destructing: 1 Destructing: 2 Destructing: 3 Constructing!:2 Copying: 2 Destructing: 2 Constructing!:4 Copying: 4 Copying: 1 Copying: 2 Copying: 3 Copying: 2 Destructing: 1 Destructing: 2 Destructing: 3 Destructing: 2 Destructing: 4 Constructing!:5 Copying: 5 Destructing: 5 prepare finished! =========================================== Constructing!:2 Destructing: 2 Constructing!:2 Destructing: 2 Constructing!:2 Destructing: 2 Assigning: 3 Constructing!:2 Destructing: 2 Constructing!:2 Destructing: 2 Assigning: 4 Constructing!:2 Destructing: 2 Assigning: 5 remove finished! =========================================== Destructing: 4 Destructing: 5 erase finished! =========================================== Destructing: 1 Destructing: 3 Destructing: 4 Destructing: 5
注意:中间的很多“Destructing: 2”估计是析构临时对象,请忽略!
由此可见erase才是真正释放空间的操作。
由这个代码的输出可以看出来,C++0x中的右值引用以及move语义编程是多么重要啊,如果加上这个特性,开始位置就不会出现临时对象多频繁构造和析构了!
posted on 2012-12-01 16:46 William.Wu 阅读(163) 评论(0) 编辑 收藏 举报