在意外功能结束时进行清理,标准等效

Cleanup at unexpected function end, std equivalent

本文关键字:标准 功能 意外 结束      更新时间:2023-10-16

我有一些函数,我需要使用成员变量(自定义类的向量(。
在此函数结束时,需要清除此成员,但它需要在此函数的持续时间内保持为成员。 另一个问题是,由于程序的自定义错误处理,函数可能会过早结束。然而,该成员仍需要清除。

我首先使用 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;
}