在意外的函数结束时进行清理,等效于标准 [英] Cleanup at unexpected function end, std equivalent

查看:62
本文介绍了在意外的函数结束时进行清理,等效于标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些需要使用成员变量(自定义类的向量)的函数。

在此函数结束时,需要清除该成员,但需要保留为成员在此功能期间。
另一个问题是,由于程序的自定义错误处理,该函数可能过早结束。

I have some function where I need to use a member variable(a vector of custom classes).
At the end of this function this member needs to be cleared but it needs to stay as a member for the duration of this function. Another problem is that the function can end prematurely due to custom error handling of the program. Yet the member still needs to be cleared.

我首先使用std :: move在本地变量的开头移动了该成员。
效果很好,但现在看来我需要将该变量保留为成员变量,直到该函数结束。

I first moved this member at the beginning in a local variable using std::move. This worked pretty well but it now turns out I need the variable to stay as a member variable till the end of that function.

我想出了

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

也欢迎使用任何更清洁的解决方案,但我的实际问题如下。

是否有与我使用的Clean类等效的std?

Any cleaner solutions are also welcome but my actual question is the following.
Is there any std equivalent of the Clean class I used?

Ps:使用g ++ 5.3.0为我编译代码片段

Ps: code fragment compiles for me using g++ 5.3.0


g ++ -std = c ++ 14 -o main main.cpp

g++ -std=c++14 -o main main.cpp


推荐答案

感谢评论和其他问题,我得到了这个结果:

This is the result I came to thanks to comments and other questions:

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

这篇关于在意外的函数结束时进行清理,等效于标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆