Skip to content

Commit 444f704

Browse files
committed
Applied Bjarne's and Neil's feedback
1 parent a0137d5 commit 444f704

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

docs/gsl-intro.md

+17-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
by Herb Sutter
55

6-
updated 2017-04-17
6+
updated 2017-05-24
77

88

99
## Overview: "Is this document a tutorial or a FAQ?"
@@ -21,10 +21,16 @@ First look at the [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuideli
2121

2222
You can try out the examples in this document on all major compilers and platforms using [this GSL reference implementation](https://github.com/microsoft/gsl).
2323

24-
# gsl::span: "What is gsl::span for?"
24+
25+
# gsl::span: "What is gsl::span, and what is it for?"
2526

2627
`gsl::span` is a replacement for `(pointer, length)` pairs to refer to a sequence of contiguous objects. It can be thought of as a pointer to an array, but that knows its bounds.
2728

29+
For example, a `span<int,7>` refers to a sequence of seven contiguous `int`s.
30+
31+
A `span` does not own the elements it points to. It is not a container like an `array` or a `vector`, it is a view into the contents of such a container.
32+
33+
2834
## span parameters: "How should I choose between span and traditional (ptr, length) parameters?"
2935

3036
In new code, prefer the bounds-checkable `span<T>` instead of separate pointer and length parameters. In older code, adopt `span` where reasonable as you maintain the code.
@@ -103,11 +109,6 @@ void dangerous_process_ints(int* p, size_t n) {
103109
for (auto i = 0; i < n; ++i) {
104110
p[i] = next_character();
105111
}
106-
107-
// or:
108-
// while (n--) {
109-
// *p = next_character();
110-
//}
111112
}
112113
~~~
113114

@@ -121,6 +122,14 @@ void process_ints(span<int> s) {
121122
}
122123
~~~
123124
125+
Note that this is bounds-safe with zero overhead, because there is no range check needed -- the range-`for` loop is known by construction to not exceed the range's bounds.
126+
127+
128+
## Element access: "How do I access a single element in a span?"
129+
130+
Use `myspan[offset]` to subscript, or equivalently use `iter + offset` wheren `iter` is a `span<T>::iterator`. Both are range-checked.
131+
132+
124133
125134
## Sub-spans: "What if I need a subrange of a span?"
126135
@@ -254,7 +263,7 @@ void serialize(span<const byte>); // can't forget const, the first test call sit
254263
void f(span<widget> s) {
255264
// ...
256265
// serialize one object's bytes (incl. padding)
257-
serialize(s.as_bytes()); // ok
266+
serialize(as_bytes(s)); // ok
258267
}
259268
~~~
260269

0 commit comments

Comments
 (0)