1

In my app I need to read some values from some source, keep them for a while in a storage, and then apply. After being applied, values are not needed and can be removed from the storage.

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
}

My question is how do I implement getValues method? Is it possible to implement it so that it clears values array in Storage after being called (using move semantics or whatsoever)? In other words, there is no need to keep values in Storage after getValues has been called once.

If it is not possible, I will have to implement additional method say Storage::clearValues which I would need to call at the end of Apply() -- this is what I am tryng to avoid.

Nick
  • 3,205
  • 9
  • 57
  • 108
  • 1
    Tangential, but I would recommend naming the method `extractValues`, `releaseValues` or similar. `get` does not usually imply that you are "stealing" something from an object. – Max Langhof Jan 30 '19 at 13:36

1 Answers1

2

Return by value from moved member:

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

From is-a-moved-from-vector-always-empty, we cannot just implement return std::move(values); :-/

Jarod42
  • 203,559
  • 14
  • 181
  • 302