Bewerken

Delen via


Warning C26437

Do not slice.

C++ Core Guidelines: ES.63: Don't slice

The language allows slicing and can be viewed as a special case of a dangerous implicit cast. Even if it's done intentionally and doesn't lead to immediate issues, it's still highly discouraged. It makes code harder to change, by forcing extra requirements on related data types. It's especially true if types are polymorphic or involve resource management.

Remarks

This rule warns not only on explicit assignments, but also on implicit slicing. Implicit slicing happens when a result gets returned from the current function, or when data gets passed to other functions.

The rule also flags cases where an assignment doesn't involve real data slicing (for example, if types are empty or don't make any dangerous data manipulations). Such warnings should still be fixed to prevent any undesirable regressions if data types or behaviors change in the future.

Example

In the next code example, we read id_ex, but the caller of the function will only get a slice of the object:

struct id {
    int value;
};

struct id_ex : id {
    int extension;
};

bool read_id(stream &s, id &v) {
    id_ex tmp{};
    if (!s.read(tmp.value) || !s.read(tmp.extension))
        return false;

    v = tmp; // C26437
    return true;
}

To fix the issue, update the function to use the correct types:

// ...
bool read_id(stream &s, id_ex &v) {
// ...