C26449 NO_SPAN_FROM_TEMPORARY
gsl::span or std::string_view created from a temporary will be invalid when the temporary is invalidated.
C++ Core Guidelines: GSL.view: Views.
Spans and views are convenient and lightweight types that allow to reference memory buffers. But they must be used carefully: while their interface looks similar to standard containers, their behavior is more like the behavior of pointers and references. They do not own data and must never be constructed from temporary buffers. This check focuses on cases where source data is temporary, while span or view is not. There is another check which handles slightly different scenario involving span references: C26445 NO_SPAN_REF. Both rules can help to avoid subtle but dangerous mistakes made when legacy code gets modernized and adopts spans or views.
Remarks
- This rule warns on places where constructors get invoked for spans or views and the source data buffer belongs to a temporary object created in the same statement. This includes:
- implicit conversions in return statements;
- implicit conversions in ternary operators;
- explicit conversions in
static_castexpressions; - function calls that return containers by value.
- Temporaries created for function call arguments are not flagged. It is safe to pass spans from such temporaries if target functions don’t retain data pointers in external variables.
- If spans or views are themselves temporaries, the rule skips them.
- Data tracking in the checker has certain limitations; therefore complex scenarios involving multiple or obscure reassignments may not be handled.
Example: Subtle difference in result types
// Returns a predefined collection. Keeps data alive.
gsl::span<const sequence_item> get_seed_sequence() noexcept;
// Returns a generated collection. Doesn’t own new data.
const std::vector<sequence_item> get_next_sequence(gsl::span<const sequence_item>);
void run_batch()
{
auto sequence = get_seed_sequence();
while (send(sequence))
{
sequence = get_next_sequence(sequence); // C26449
// ...
}
}
Povratne informacije
Pošalјite i prikažite povratne informacije za