1

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++?

Joe
  • 7,378
  • 4
  • 37
  • 54
  • 2
    more about `span` [here](https://stackoverflow.com/questions/45723819/what-is-a-span-and-when-should-i-use-one) – default Nov 03 '17 at 08:22

1 Answers1

6

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.

  • 3
    In addition to the questions you have asked, I would add "can the pointer be null?", and "what are the ownership semantics?" (the answer to the latter *should* be that the call**er** owns the data - but there are enough legacy APIs for it still be a question one has to ask). – Martin Bonner supports Monica Nov 03 '17 at 08:38