Warning C26445
Do not assign
gsl::span
orstd::string_view
to a reference. They are cheap to construct and are not owners of the underlying data. (gsl.view)
A reference to gsl::span
or std::string_view
may be an indication of a lifetime issue.
C++ Core Guidelines
This rule catches subtle lifetime issues that may occur in code migrated from standard containers to new span and view types. Such types can be considered as "references to buffers." Using a reference to a span or view creates an extra layer of indirection. Such indirection is often unnecessary and can be confusing for maintainers. Spans are cheap to copy and can be returned by value from function calls. Obviously, such call results should never be referenced.
Remarks
- The rule detects references to gsl::span<>, gsl::basic_string_span<>, and std::basic_string_view<> (including aliases to instantiations).
- Currently warnings are emitted only on declarations and return statements. This rule may be extended in future to also flag function parameters.
- The implementation of this rule is lightweight doesn't attempt to trace actual lifetimes. Using of references may still make sense in some scenarios. In such cases, false positives can safely be suppressed.
Code analysis name: NO_SPAN_REF
Example
Reference to a temporary:
// Old API - uses string reference to avoid data copy.
const std::string& get_working_directory() noexcept;
// New API - after migration to C++17 it uses string view.
std::string_view get_working_directory() noexcept;
// ...
// Client code which places an explicit reference in a declaration with auto specifier.
const auto &wd = get_working_directory(); // C26445 after API update.