Muokkaa

Jaa


Warning C26401

Do not delete a raw pointer that is not an owner<T> (i.11)

Remarks

This check detects code where moving to owner<T> can be a good option for the first stage of refactoring. Like C26400, it enforces rules I.11 and R.3, but focuses on the "release" portion of the pointer lifetime. It warns on any call to operator delete if its target isn't an owner<T> or an implicitly assumed owner. For more information about auto declarations, see C26400. This check includes expressions that refer to global variables, formal parameters, and so on.

Warnings C26400 and C26401 always occur with C26409, but they're more appropriate for scenarios where immediate migration to smart pointers isn't feasible. In such cases, the owner<T> concept can be adopted first, and C26409 may be temporarily suppressed.

Code analysis name: DONT_DELETE_NON_OWNER

See also

C++ Core Guidelines I.11

Examples

struct myStruct {};

myStruct* createMyStruct();
void function()
{
    myStruct* pMyStruct = createMyStruct();
    // ...
    delete pMyStruct; // C26401. Do not delete a raw pointer that is not an owner<T>
}

See that C26401 is removed if ownership of the pointer is indicated by gsl::owner.

#include <gsl/pointers>
struct myStruct {};

gsl::owner<myStruct*> createMyStruct();
void function()
{
    gsl::owner<myStruct*> pMyStruct = createMyStruct();
    // ...
    delete pMyStruct; // no warning.
}

There's a C++ idiom that triggers this warning: delete this. The warning is intentional, because the C++ Core Guidelines discourage this pattern. You can suppress the warning by using the gsl::suppress attribute, as shown in this example:

class MyReferenceCountingObject final
{
public:
    void AddRef();
    void Release() noexcept
    {
        ref_count_--;
        if (ref_count_ == 0)
        {
            [[gsl::suppress(i.11)]]
            delete this; 
        }
    }
private:
    unsigned int ref_count_{1};
};