以下代码演示了一种确保向量完全释放的技巧:
#include <vector>
using namespace std;
template<typename T>
class tvector : public vector<T>
{
public:
typedef vector<T> base;
void swap(tvector<T>& v) {
// do some other stuff, but omitted here.
base::swap(v); }
};
int main()
{
tvector<int> tv1;
// imagine filling tv1 with loads of stuff, use it for something...
// now by swapping with a temporary declaration of an empty tvector that should
// go out of scope at the end of the line, we get all memory used …Run Code Online (Sandbox Code Playgroud)