At CppCon 2015, we heard about the CppCoreGuildelines and a supporting library for it, the GSL. There were several talks devoted to this, including two of the keynotes, and we were promised a future of zero cost abstractions that were also safe. What’s not to like?
Me being me, I had to try this out for myself. And what better way than when rewriting my C++ implementation of an MQTT broker from scratch. Why from scratch? The version I had didn’t perform well, required extensive refactoring to do so and I’m not crazy enough to post results from C++ that lose by a factor of 3 to any other language.
It was a good fit as well: the equivalent D and Rust code was using slices, so this seemed like the perfect change to try out gsl::span (née gsl::array_view).
I think I liked it. I say I think because the benefits it provided (slices in C++!) are something I’m used to now by programming in D, and of course there were a few things that didn’t work out so well, namely:
gsl::cstring_span
First of all, there was this bug I filed. This is a new one to shoot oneself in one’s foot and we were not amused. Had I just declared a function taking const std::string& as usual, I wouldn’t have hit the bug. The price of early adoption, I guess. The worst part is that it failed silently and was hard to detect: the strings printed out the same, but one had a silent terminating null char. I ended up having to declare an overload that took const char* and did the conversion appropriately.
Also, although I know why, it’s still incredibly annoying to have to use empty angle brackets for the default case.
Rvalues need not apply
Without using the GSL, I can do this:
void func(const std::vector<unsigned char>&); func({2, 3, 4}); //rvalues are nice
With the GSL, it has to be this:
void func(gsl::span<const unsigned char>&); const std::vector<unsigned char> bytes{2, 3, 4}; func(bytes);
It’s cumbersome and I can’t see how it’s protecting me from anything.
Documentation
I had to refer to the unit tests (fortunately included) and Neil MacIntosh’s presentation at CppCon 2015 multiple times to figure out how to use it. It wasn’t always obvious.
Conclusion
I still think this is a good thing for C++, but the value of something like gsl::not_null is… null without the static analysis tool they mentioned. It could be easier to use as well. My other concern is how and if gsl::span will work with the ranges proposal / library.
Thanks for taking the plunge and sharing!
Did the GSL makers act on your bug report?
It was a known limitation, so it got closed. I haven’t updated or tried it again since, so I don’t know if it’s been fixed or not.