| description | Learn more about: Warning C26402 DONT_HEAP_ALLOCATE_MOVABLE_RESULT | ||
|---|---|---|---|
| title | Warning C26402 | ||
| ms.date | 08/20/2020 | ||
| f1_keywords |
|
||
| helpviewer_keywords |
|
||
| ms.assetid | b9d3d398-697a-4a5d-8bfe-9c667dffb90b |
Return a scoped object instead of a heap-allocated if it has a move constructor (r.3).
To avoid confusion about whether a pointer owns an object, a function that returns a movable object should allocate it on the stack. It should then return the object by value instead of returning a heap-allocated object. If pointer semantics are required, return a smart pointer instead of a raw pointer. For more information, see C++ Core Guidelines R.3: Warn if a function returns an object that was allocated within the function but has a move constructor. Suggest considering returning it by value instead.
This example shows a bad_example function that raises warning C26409. It also shows how function good_example doesn't cause this issue.
// C26402.cpp
struct S
{
S() = default;
S(S&& s) = default;
};
S* bad_example()
{
S* s = new S(); // C26409, avoid explicitly calling new.
// ...
return s; // C26402
}
// Prefer returning objects with move contructors by value instead of unnecessarily heap-allocating the object.
S good_example() noexcept
{
S s;
// ...
return s;
}