Assign to array that can allow NULL members, without using the heap?

If you want an object with automatic storage that has optional semantics (i.e. may or may not exist), you can use boost::optional.

boost::optional<T> is a container that can have zero or one elements. If it is empty, it doesn’t store a T object, just like an empty vector doesn’t store any object. In fact, you can think of boost::optional<T> as as std::vector<T> whose capacity is always 1 and cannot grow. And since the storage size required for this is fixed and known at compile-time (it’s sizeof(T)), boost::optional doesn’t need any dynamic allocation.

Leave a Comment