首页 > 解决方案 > 数据返回一次后如何从类实例中删除数据

问题描述

在我的应用程序中,我需要从某个来源读取一些值,将它们保存在存储中一段时间​​,然后应用。应用后,不需要值,可以从存储中删除。

class Storage: public Singleton<...> {
public:
    void addValue(int v) {values.push_back(v);}
    // ...
private:
    std::vector<int> values;
    // ...
}

// read values from some source and keep them in the storage
void Init() {
    for (...) {
        Storage::Instance()->addValue(...);
    }
}

// a few seconds later...

// apply values somehow and get rid of them
void Apply() {
    auto &&values = Storage::Instance()->getValues();
    // ideally, at this point Storage must not contain values array
    // process values somehow
    for auto i: values {
    // ...
    }
    // values are not needed any longer
}

我的问题是如何实现getValues方法?是否可以实现它以便values在调用后清除数组Storage(使用移动语义或其他方式)?换句话说,没有必要values在被调用一次Storage后保留。getValues

如果不可能,我将不得不实施额外的方法,说Storage::clearValues我需要在最后调用Apply()- 这是我试图避免的。

标签: c++c++11move-semantics

解决方案


从移动的成员按值返回:

class Storage
{
public:
    void addValue(int v) {values.push_back(v);}
    std::vector<int> takeValues() {
        std::vector<int> res = std::move(values);
        values.clear();
        return res;
    }
private:
    std::vector<int> values;
};

is-a-moved-from-vector-always-empty,我们不能只实现return std::move(values);:-/


推荐阅读