c++ - 数据返回一次后如何从类实例中删除数据
问题描述
在我的应用程序中,我需要从某个来源读取一些值,将它们保存在存储中一段时间,然后应用。应用后,不需要值,可以从存储中删除。
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()
- 这是我试图避免的。
解决方案
从移动的成员按值返回:
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);
:-/
推荐阅读
- python - 我试图学习 scikit,但停留在关于编码器的代码要求他们的输入是统一的字符串或数字
- php - Jquery问题将数据发送到php
- webrtc - 使用自定义 TURN/STUN/ICE 服务器
- amazon-web-services - AWS 安全组为动态 IP 添加入站 IP 规则
- python - 相机在 .exe 文件项目中没有响应
- python - 'int(input())' 是什么意思?
- string - VBS剪切字符串的第一行
- javascript - 为什么在加入响应块时发送了 4 个请求?
- python - 如果评论太多,YouTube评论提取器无限循环
- python - 如何在 Matplotlib 的 X 轴上绘制日文格式的日期?