【发布时间】:2011-11-03 12:48:20
【问题描述】:
以下代码演示了确保向量完全解除分配的技巧:
#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 by tv1 returned
// to the heap
tv1.swap(tvector<int>());
}
嗯,这可以使用 Visual C++ (cl.exe),但使用 GNU g++ 无法编译,出现以下错误:
test.cpp: In function ‘int main()’:
test.cpp:18:28: error: no matching function for call to ‘tvector<int>::swap(tvector<int>)’
test.cpp:10:7: note: candidate is: void tvector<T>::swap(tvector<T>&) [with T = int]
这是 g++ 中的错误,还是我的代码确实是错误的 C++ 代码?
我使用 g++ 的这种释放技巧的解决方法是:
int main()
{
tvector<int> tv1;
{
tvector<int> t;
tv1.swap(t);
}
}
对此有何看法?
【问题讨论】:
-
我的观点是,既然它即将超出范围,你应该什么都不做,让析构函数清理它。
-
没有。不要从标准容器继承。不要冒险。
-
这对传统的
swap技巧有何改进?另请注意,感谢shrink_to_fit,C++11 使这个问题变得不那么重要了。 -
@KerrekSB:
shrink_to_fit没有任何保证。由实现决定是否应该进行释放。真正的问题是“std::vector<int>().swap(v);与v = std::vector<int>()相比有何改进”。
标签: c++ visual-c++ g++