Mar*_*inD 2 c++ g++ visual-c++
以下代码演示了一种确保向量完全释放的技巧:
#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>());
}
Run Code Online (Sandbox Code Playgroud)
好吧,这可以使用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]
Run Code Online (Sandbox Code Playgroud)
这是g ++中的错误,还是我的代码真的错误的C++代码?
我使用g ++解决这个问题的方法是:
int main()
{
tvector<int> tv1;
{
tvector<int> t;
tv1.swap(t);
}
}
Run Code Online (Sandbox Code Playgroud)
有什么意见吗?
Ale*_* C. 12
这众所周知.取消分配向量内容的标准教科书技巧是:
std::vector<int> v;
// Do stuff with v
std::vector<int>().swap(v); // clears v
Run Code Online (Sandbox Code Playgroud)
请注意,反向不起作用:
v.swap(std::vector<int>()); // compile time error
Run Code Online (Sandbox Code Playgroud)
因为您试图将临时绑定到非const引用,这是禁止的.
Visual Studio允许将此作为非标准扩展,但将警告级别提升至/ W3(IIRC)会触发"非标准扩展使用"警告.
在C++ 11中(技术上也在C++ 03中!),你可以做到
v = std::vector<int>();
Run Code Online (Sandbox Code Playgroud)
或者,如果你是冗长的(仅限C++ 11),那就有了
v.clear(); // or v.resize(0);
v.shrink_to_fit();
Run Code Online (Sandbox Code Playgroud)
但是标准并不保证是否要满足收缩要求.
如果你真的需要,你可以使用它,但请不要继承标准容器.这不是一件安全的事情:你冒着调用错误析构函数的风险.