如何在数据返回一次后从 class 实例中删除数据
How to remove data from class instance after data being returned once
在我的应用程序中,我需要从某些来源读取一些值,将它们保存在存储中一段时间,然后应用。应用后,不需要值,可以从存储中删除。
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
方法?是否可以实现它以便在调用后清除 Storage
中的 values
数组(使用移动语义或其他)?换句话说,getValues
被调用一次后,values
就不需要保留在Storage
中了。
如果不可能,我将不得不实现额外的方法,比如 Storage::clearValues
,我需要在 Apply()
结束时调用它——这是我试图避免的。
Return 按移动成员的值:
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);
:-/
在我的应用程序中,我需要从某些来源读取一些值,将它们保存在存储中一段时间,然后应用。应用后,不需要值,可以从存储中删除。
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
方法?是否可以实现它以便在调用后清除 Storage
中的 values
数组(使用移动语义或其他)?换句话说,getValues
被调用一次后,values
就不需要保留在Storage
中了。
如果不可能,我将不得不实现额外的方法,比如 Storage::clearValues
,我需要在 Apply()
结束时调用它——这是我试图避免的。
Return 按移动成员的值:
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);
:-/