首页 > 解决方案 > 检查是否已将指针设置为已初始化的对象

问题描述

假设我有一个名为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以便稍后检查是否相等,但我想知道是否有更好的方法。

标签: c++c++11

解决方案


你想要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);
  }
}

推荐阅读