Skip to content

Latest commit

 

History

History
52 lines (38 loc) · 2.43 KB

File metadata and controls

52 lines (38 loc) · 2.43 KB
description Learn more about: Warning C26449 NO_SPAN_FROM_TEMPORARY
title Warning C26449
ms.date 03/22/2018
f1_keywords
C26449
NO_SPAN_FROM_TEMPORARY
helpviewer_keywords
C26449

Warning C26449

gsl::span or std::string_view created from a temporary will be invalid when the temporary is invalidated (gsl.view)

C++ Core Guidelines: GSL.view: Views.

Spans and views are convenient and lightweight types that allow you 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 don't own data and must never be constructed from temporary buffers. This check focuses on cases where source data is temporary, while a span or view isn't. There's another check that handles a 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 check includes:

    • implicit conversions in return statements;
    • implicit conversions in ternary operators;
    • explicit conversions in static_cast expressions;
    • function calls that return containers by value.
  • Temporaries created for function call arguments aren't flagged. It's 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.

Code analysis name: NO_SPAN_FROM_TEMPORARY

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
        // ...
    }
}