cppreference uses it to describe std::string_view:
std::basic_string_view
(C++17) - a lightweight non-owning read-only view into a subsequence of a string.
devtut and sodocumentation use it to describe std::string_view as well:
C++17 introduces
std::string_view
, which is simply a non-owning range ofconst char
s, implementable as either a pair of pointers or a pointer and a length.
And various other questions and answers here on SO reference it, yet I can't find any explanation of what it means.
An owner is an object containing a pointer to an object allocated by new for which a delete is required. Every object on the free store (heap, dynamic store) must have exactly one owner. If there are two pointers to an object on the free store, only one can be the owner.
Pointer variables imply ownership of the objects that they point to. When a method (or function) has a local variable that points to an object, that variable is said to own the object being pointed to.
You can own a resource, i.e. anything that there is a limited amount of. This is usually memory or system handles. Whatever owns the resource is responsible for releasing it when done using it.
std::unique_ptr
and std::shared_ptr
are examples of an owning wrapper. It releases their memory when it goes out of use. Same goes for any other RAII class.
std::basic_string_view
is non-owning, which is a nice way of saying that it is not bound to actual lifetime of the string in any way, and that, if you are not careful, it may dangle if the string reallocates.
"Owning X" means being responsible for the lifecycle of X.
In case of a std::string
the class contains an array of char
. The std::string
class is responsible for allocating and deallocating the char array; the whole time the string object owns this array.
In contrast to this std::string_view
only "knows about" such an array; It doesn't do any allocations or deallocations with it.
The benefit is that you don't need to do a copy of the array which could get expensive, the drawback is that if you aren't careful, the array could be freed before you stop using the std::string_view
which results in undefined behavior so the result could be your program crashing.
An answer to a question about std::span says:
A
span<T>
is:...
- A non-owning type (i.e. a "reference-type" rather than a "value type"): It never allocates nor deallocates anything and does not keep smart pointers alive.
The linked answer provides a good explanation of what a reference type is.
std::string_view and std::span are objects with reference semantics. isocpp's faq provides a good explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With