Edit

Share via


Warning C26407

Prefer scoped objects, don't heap-allocate unnecessarily (r.5)

To avoid unnecessary use of pointers, we try to detect common patterns of local allocations. For example, we detect when the result of a call to operator new is stored in a local variable and later explicitly deleted. This check supports the C++ Core Guidelines rule R.5: Prefer scoped objects, don't heap-allocate unnecessarily. To fix the issue, use an RAII type instead of a raw pointer, and allow it to deal with resources. Obviously, it isn't necessary to create a wrapper type to allocate a single object. Instead, a local variable of the object's type would work better.

Remarks

  • To reduce the number of warnings, code analysis only detects this pattern for owner pointers. So, it's necessary to mark owners properly first. We can easily extend this analysis to cover raw pointers if we receive feedback on the Visual Studio C++ Developer Community from customers in support of such scenarios.

  • The scoped object term may be a bit misleading. In general, we suggest you use either a local variable whose lifetime is automatically managed, or a smart object that efficiently manages dynamic resources. Smart objects can do heap allocations, but it's not explicit in the code.

  • If the warning fires on array allocation, which is often needed for dynamic buffers, you can fix it by using standard containers, or std::unique_pointer<T[]>.

  • The pattern is detected only for local variables. We don't warn in cases where an allocation is assigned to, say, a global variable and then deleted in the same function.

Code analysis name: DONT_HEAP_ALLOCATE_UNNECESSARILY

Example 1: Unnecessary object allocation on heap

auto tracer = new Tracer();
ScanObjects(tracer);
delete tracer;  // C26407

Example 2: Unnecessary object allocation on heap (fixed with local object)

Tracer tracer;  // OK
ScanObjects(&tracer);

Example 3: Unnecessary buffer allocation on heap

auto value = new char[maxValueSize];
if (ReadSetting(name, value, maxValueSize))
    CheckValue(value);
delete[] value; // C26407

Example 4: Unnecessary buffer allocation on the heap (fixed with container)

auto value = std::vector<char>(maxValueSize); // OK
if (ReadSetting(name, value.data(), maxValueSize))
    CheckValue(value.data());