Rediger

Del via


Warning C26400

Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead (i.11)

Remarks

This check helps to enforce the *rule I.11: Never transfer ownership by a raw pointer (T*), which is a subset of the rule R.3: A raw pointer (a T*) is non-owning. Specifically, it warns on any call to operator new, which saves its result in a variable of raw pointer type. It also warns on calls to functions that return gsl::owner<T> if their results are assigned to raw pointers. The idea is that you should clearly state ownership of memory resources. For more information, see the C++ Core Guidelines.

The easiest way to fix this warning is to use auto declaration if the resource is assigned immediately at the variable declaration. If this fix isn't possible, then we suggest that you use the type gsl::owner<T>. The auto declarations initialized with operator new are "owners" because we assume that the result of any allocation is implicitly an owner pointer. We transfer this assumption to the auto variable and treat it as owner<T>.

If this check flags a call to a function that returns owner<T>, it may be an indication of a legitimate bug in the code. Basically, it points to a place where the code leaks an explicit notion of ownership (and maybe the resource itself).

This rule currently checks only local variables. If you assign an allocation to a formal parameter, global variable, class member, and so on, it's not flagged. Appropriate coverage of such scenarios is planned for future work.

Code analysis name: NO_RAW_POINTER_ASSIGNMENT

Example 1: Simple allocation

char *buffer = nullptr;
if (useCache)
    buffer = GetCache();
else
    buffer = new char[bufferSize];  // C26400

Example 2: Simple allocation (fixed with gsl::owner<T>)

gsl::owner<char*> buffer = nullptr;
if (useCache)
    buffer = GetCache();
else
    buffer = new char[bufferSize];  // OK

Example 3: Simple allocation (fixed with auto)

auto buffer = useCache ? GetCache() : new char[bufferSize]; // OK