次の方法で共有


警告 C26474

変換が暗黙的になる可能性がある場合はポインター型間ではキャストしないでください。

C++ Core Guidelines:
Type.1: キャストを避ける

場合によっては、ポインター型間の暗黙的なキャストは安全であり、特定のキャスト式を記述する必要がありません。 このルールは、安全に削除できる不要なキャストのインスタンスを検索します。

解説

ルール ID は、"暗黙的なキャストは許容される場合に使用されない" と解釈される必要があります。

このルールは、ポインターにのみ適用されます。 静的キャストをチェックし、キャストを再解釈します。

次の場合は、明示的なキャスト式を使用してはいけない、許容可能なポインター変換です。

  • nullptr_t への変換
  • void* への変換
  • 派生型によって非表示にされている基本メンバー関数を呼び出すときに、派生型からその基底クラスへの変換

例 1

この例では、不要な変換によって論理エラーが非表示になります。

template<class T>
bool register_buffer(T buffer) {
    auto p = reinterpret_cast<void*>(buffer); // C26474, also 26490 NO_REINTERPRET_CAST
    // To fix, declare buffer as T*, and use this to define p:
    // auto p = buffer;
    return buffers_.insert(p).second;
}

void merge_bytes(std::uint8_t *left, std::uint8_t *right)
{
    if (left && register_buffer(*left)) { // Unintended dereference!
        // ...
        if (right && register_buffer(right)) {
            // ...
        }
    }
}

例 2

この例では、キャストを使用して基底クラスのメンバー関数にアクセスする方法を示します。

struct struct_1
{
    void foo();
    void bar();
};

struct struct_2 : struct_1
{
    void foo(); // this definition hides struct_1::foo
};

void fn(struct_2* ps2)
{
    static_cast<struct_1*>(ps2)->foo(); // This cast is necessary to access struct_1::foo
                                        // Alternatively, use ps2->struct_1::foo();
    static_cast<struct_1*>(ps2)->bar(); // This cast is unnecessary and can be done implicitly
}