title | description | ms.date | f1_keywords | helpviewer_keywords | ||
---|---|---|---|---|---|---|
C26400 |
Describes the Microsoft C/C++ code analysis warning C26400, its causes, and how to address it. |
10/23/2020 |
|
|
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 here 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.
char *buffer = nullptr;
if (useCache)
buffer = GetCache();
else
buffer = new char[bufferSize]; // C26400
gsl::owner<char*> buffer = nullptr;
if (useCache)
buffer = GetCache();
else
buffer = new char[bufferSize]; // OK
auto buffer = useCache ? GetCache() : new char[bufferSize]; // OK