Search code examples
c++cpp-core-guidelinesguideline-support-library

gsl::span - pointer to end


I need to pass a gsl::span to a function that expects a pointer to beginning and a pointer to end. I updated the function to use a gsl::span to avoid a do not use pointer arithmetic warning. So how do I get the pointer to the end?

I am trying to call std::ctype::widen. What magical incantation do I use to get the value of the end parameter to the std::ctype::widen function?

I tried the following.

&(*str.cend())

I also tried the following.

&str[srcLen]

Both result in a crash.

I could try the following but it would just cause the very warning I was trying to resolve in the first place.

str.data() + str.length()

I am beginning to think that the whole C++ Core Guidelines and the Guidelines Support Library are too poorly thought out to be worth the effort. This is the second time I encountered a "gsl causes the exact warning I was trying to resolve in the first place" issue.


Solution

  • span is, like most of the C++ library, intended to be used with code that accepts template iterators. You can pass begin/end to algorithms or other containers and so forth.

    Such APIs don't work nearly as well when you have to deal with an interface based purely on specific iterator pairs like pointers. It's no different from trying to get a pointer to the end of a std::vector; you're going to have to do pointer arithmetic sooner or later.

    But if you're annoyed by warnings about pointer arithmetic, try using std::next(str.data(), str.size()) to compute the end pointer. The static analysis tool might complain about that, but it really shouldn't.