c++ - 检查是否已将指针设置为已初始化的对象
问题描述
假设我有一个名为Entry
:
template <typename K, typename V>
class Entry {
public:
Entry(K const &key, V const &val, size_t const hash_val) :
key(key), val(val), hash_val(hash_val), empty(false){
}
K getKey() const {
return key;
}
V getValue() const {
return val;
}
size_t getHash() const {
return hash_val;
}
bool isEmpty() const{
return empty;
}
private:
// key-value pair
K key;
V val;
// Store hash for reallocation
size_t hash_val;
// Store empty state
bool empty;
};
然后我创建一个对象数组
Entry<K, V>** entries = new Entry<K, V> *[100];
如果我打电话entries[0]->isEmpty()
,我会遇到分段错误。这对我来说很有意义,因为我实际上并没有在内存中实例化一个新对象。但是,我希望能够检查数组中的插槽是否实际上指向有效对象。目前,我一直在设置每个指针,nullptr
以便稍后检查是否相等,但我想知道是否有更好的方法。
解决方案
你想要optional
。它始终要么是有效对象,要么处于“空”状态。
#include <cstdio>
#include <optional>
#include <vector>
struct Foo {
int bar;
};
int main() {
std::vector<std::optional<Foo>> vfoo{
Foo{1}, std::nullopt, Foo{2}, Foo{3}, std::nullopt,
};
for (auto const& foo : vfoo) {
if (!foo)
std::puts("Not Initialized");
else
std::printf("Foo{%d}\n", foo->bar);
}
}
推荐阅读
- ios - 如何在任务切换器中显示锁定屏幕并正确恢复
- ios - ARKit 快照给出了变形的模型
- javascript - 使用 javascript 在单页应用程序中获取以前的站点 url
- asp.net - 间歇性 IndexOutOfRangeException 提示缺少 SQL 列,但已通过 IIS 回收解决
- jquery - 为什么我的用户输入字段在提交后不会重置?
- c++ - IntelMPI 错误(适用于 openMPI)
- python - 为 py-elasticsearch-dsl 中的索引创建自定义分析器过滤器
- python - 在 Python 中,在线程之间共享类实例数据和方法,但只有一个特定变量
- openssl - 将 DER 编码的 RSA 公钥与 OpenSSL 一起使用
- php - php中的日期时间差