gpt4 book ai didi

C++ 确保释放 vector 的技巧,但 GNU g++ 存在编译问题

转载 作者:太空狗 更新时间:2023-10-29 23:25:00 26 4
gpt4 key购买 nike

下面的代码演示了一个确保 vector 完全释放的技巧:

#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);
}
}

对此有何看法?

最佳答案

这都是众所周知的。释放 vector 内容的标准教科书技巧是:

std::vector<int> v;
// Do stuff with v

std::vector<int>().swap(v); // clears v

请注意,反向不起作用:

v.swap(std::vector<int>()); // compile time error

因为您试图将一个临时变量绑定(bind)到一个非常量引用,这是被禁止的。

Visual Studio 允许将此作为​​非标准扩展,但将警告级别提高到/W3 (IIRC) 会触发“使用非标准扩展”警告。

在 C++11 中(技术上在 C++03 中也是如此!),你可以简单地做

v = std::vector<int>();

或者,如果你喜欢冗长(仅限 C++11),那么有

v.clear(); // or v.resize(0);
v.shrink_to_fit();

但标准不保证是否满足收缩请求。

如果确实需要,您可以使用它,但请不要从标准容器继承。这不是一件安全的事情:你冒着调用错误析构函数的风险。

关于C++ 确保释放 vector 的技巧,但 GNU g++ 存在编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7995127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com