在意外功能结束时进行清理,标准等效
Cleanup at unexpected function end, std equivalent
我有一些函数,我需要使用成员变量(自定义类的向量(。
在此函数结束时,需要清除此成员,但它需要在此函数的持续时间内保持为成员。 另一个问题是,由于程序的自定义错误处理,函数可能会过早结束。然而,该成员仍需要清除。
我首先使用 std::move 在局部变量中移动了这个成员。 这工作得很好,但现在事实证明我需要变量作为成员变量保留,直到该函数结束。
我想出了以下解决方案,使用带有引用的unique_ptr,该参考将在破坏时进行移动。
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
template <class T>
class Clean
{
public:
Clean(T& clean)
: m_clean(clean) {}
~Clean()
{
T destroy = move(m_clean);
}
private:
T& m_clean;
};
class A
{
public:
A()
{
m_numbers = { { 3, 1 ,4, 1, 5} };
}
void display()
{
auto cleanNumbers = make_unique<Clean<vector<int> > >(m_numbers);
for(int number: m_numbers)
cout << number << endl;
}
private:
vector<int> m_numbers;
};
int main()
{
A a;
a.display();
cout << "should be empty now" << endl;
a.display();
return 0;
}
也欢迎任何更清洁的解决方案,但我的实际问题如下。
是否有与我使用的清洁类等效的 std?
Ps:代码片段使用 g++ 5.3.0 为我编译
g++ -std=c++14 -o main main.cpp
这是我通过评论和其他问题得出的结果:
void display()
{
auto cleanNumber = [](decltype(m_numbers)* numbers){
if(numbers)
numbers->clear();
};
auto pClean = std::unique_ptr<decltype(m_numbers), decltype(cleanNumber)>(&m_numbers, cleanNumber);
for(int number: m_numbers)
cout << number << endl;
}
您可以使用shared_ptr的自定义删除器来获得相同的结果。
void A::display()
{
std::shared_ptr<int> dummy (
(int*)alloca(sizeof(int)), // very fast allocate on stack
[&](int*) { this->m_numbers.clear(); }
);
for(int number: m_numbers)
cout << number << endl;
}
这是整个代码,编译得很好,gcc 5.3 -Wall -wpedantic -march=native -std=c++14
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class A
{
public:
A()
{
m_numbers = { { 3, 1 ,4, 1, 5} };
}
void display()
{
std::shared_ptr<int> dummy (
(int*)alloca(sizeof(int)),
[&](int*) { this->m_numbers.clear(); }
);
for(int number: m_numbers)
cout << number << endl;
}
private:
vector<int> m_numbers;
};
int main()
{
A a;
a.display();
cout << "should be empty now" << endl;
a.display();
return 0;
}
相关文章:
- 为什么 C++ 标准库中没有 SIMD 功能?
- C++没有标准功能的立方体根查找器
- 如何将标准::矢量插入具有自定义排序功能的 std::set 中
- 标准::矢量的擦除功能
- 如何(以及谁可以)实现C++委员会定义的标准库功能
- 在意外功能结束时进行清理,标准等效
- 使用多个参数将成员功能指针转换为标准C函数
- 剪辑功能的标准库版本
- 包装介绍标准功能
- 标准::地图比较功能
- C 1Z标准如何定义模板功能声明中属性的正确位置
- 如何为标准功能分配空间并做记忆
- C++的最后一个位置是否有计算单元的标准功能
- 标准::功能与标准功能
- 是否可以保证C++标准库容器调用可替换的新功能
- 标准功能要求
- 提升::工厂和标准::功能
- C++11 标准::功能和完美的转发
- C++11 标准::功能比虚拟调用慢
- Eclipse C.D.T. 无法识别标准功能或"NULL"