This diagnostic rule is based on the R.5 CppCoreGuidelines rule (Prefer scoped objects, don't heap-allocate unnecessarily).
Storage for a local variable is allocated dynamically and deallocated before execution leaves the function. In this case, it is better to stack-allocate the variable to avoid the overhead due to memory allocation and deallocation.
Consider the following example:
class Object { .... };
void DoSomething()
{
auto obj = new Object;
....
delete obj;
}
Since the variable exists only within the current scope, allocation can be avoided in most cases.
Fixed version:
void DoSomething()
{
Object obj;
....
}
The warning is not issued if the previously allocated storage is not deallocated or if the address leaks outside. The following snippet demonstrates returning a pointer using a function's output parameter:
void DoSomething(Object** ppObj)
{
auto obj = new Object;
if (obj->good())
{
*ppObj = obj;
return;
}
delete obj;
}