Search code examples
c++composition

Is this mapping between C++ class member cardinality and declaration OK?


I have three kinds of cardinality for class(structure) members in my design.

  • 0 or 1
  • 0 or more
  • exactly one

I have mapped them to following declaration as class(structure) members

class Foo {
        ExactlyOnce exactlyOnce;
        std::unique_ptr<ZeroOrOnce> zeroOrOnce;
        std::list<std::shared_ptr<ZeroOrMore>> zeroOrMore;
};

I'm planning to generalize this pattern throughout the whole package, is this approach OK or it has some bugs w.r.t. member cardinality?


Solution

  • It seems fine.

    Consider the following though:

    • using boost::optional for ZeroOrOne (if you already use boost); the intent behind it is more explicit as the API is optimized for this.

    • using std::vector<T> instead of std::list<std::shared_ptr<T>> for ZeroOrMore. Outside of the case when you have large/expensive objects and perform front and random insertions, a vector tends to be more efficient.