Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
Avoid calling
newanddeleteexplicitly, usestd::make_unique<T>instead (r.11).
Even if code is clean of calls to malloc and free, we still suggest that you consider better options than explicit use of operators new and delete.
C++ Core Guidelines:
R.11: Avoid calling new and delete explicitly
The ultimate fix is to use smart pointers and appropriate factory functions, such as std::make_unique.
Remarks
- The checker warns on calls to any kind of operator
newordelete: scalar, vector, overloaded versions (global and class-specific), and placement versions. The placementnewcase may require some clarifications in the Core Guidelines for suggested fixes, and may be omitted in the future.
Code analysis name: NO_NEW_DELETE
Examples
This example shows C26409 is raised for explicit new and delete. Consider using smart pointer factory functions such as std::make_unique instead.
void f(int i)
{
int* arr = new int[i]{}; // C26409, warning is issued for all new calls
delete[] arr; // C26409, warning is issued for all delete calls
auto unique = std::make_unique<int[]>(i); // prefer using smart pointers over new and delete
}
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};
};