Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 数据返回一次后如何从类实例中删除数据_C++_C++11_Move Semantics - Fatal编程技术网

C++ 数据返回一次后如何从类实例中删除数据

C++ 数据返回一次后如何从类实例中删除数据,c++,c++11,move-semantics,C++,C++11,Move Semantics,在我的应用程序中,我需要从某些来源读取一些值,将它们保存在存储器中一段时间,然后应用。应用后,不需要值,可以从存储器中删除这些值 class Storage: public Singleton<...> { public: void addValue(int v) {values.push_back(v);} // ... private: std::vector<int> values; // ... } // read values

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

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
}
类存储:公共单例{
公众:
void addValue(int v){values.push_back(v);}
// ...
私人:
std::向量值;
// ...
}
//从某些源读取值并将其保存在存储器中
void Init(){
对于(…){
存储::实例()->addValue(…);
}
}
//几秒钟后。。。
//以某种方式应用值并将其清除
无效应用(){
auto&&values=Storage::Instance()->getValues();
//理想情况下,此时存储不能包含数组值
//以某种方式处理价值观
对于自动i:值{
// ...
}
//不再需要值
}
我的问题是如何实现
getValues
方法?是否可以实现它,以便在调用后(使用移动语义或其他方法)清除
存储中的
数组?换句话说,在调用
getValues
一次之后,不需要在
存储中保存


如果不可能,我必须实现额外的方法,比如说
Storage::clearValues
,我需要在
Apply()
末尾调用它——这就是我试图避免的。

从移动的成员按值返回:

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;
};
类存储
{
公众:
void addValue(int v){values.push_back(v);}
std::vector takeValues(){
std::vector res=std::move(值);
value.clear();
返回res;
}
私人:
std::向量值;
};

从中,我们不能只实现
返回std::move(值):-/

相切,但我建议将方法命名为
extractValues
releaseValues
或类似名称
get
通常并不意味着你在“偷”某个对象的东西。