Search code examples
c++cpp-core-guidelines

Meaning of f(T*, int) interfaces vs. f(span<T>) interfaces in core cpp guidelines


Section P3 of the core cpp guidelines offers up the following pattern under its enforcement section:

f(T*, int) interfaces vs. f(span) interfaces

Can anyone explain what it means to a crusty old C programmer looking to understand modern C++?


Solution

  • Section P3 is about "Express intent". The idea is therefore which one expresses the intention more clearly.

    Consider f(T*, int). We have to ask:

    1. Does the pointer point to a single object or an array?
    2. Does the integer represent the array size or something else?

    The information are not well expressed in the function signature. It must be obtained through other means, e.g. documentations, naming conventions, etc.

    On the other hand, when we see f(span<T>) has a clear and unquestionable intention: The function takes an array (referenced through a span<T> object). The intention is clear because this is the sole purpose of span, unlike pointer being multi-purpose.

    So, f(span<T>) states the intention better if the intention is to takes an array.