Muokkaa

Jaa


Warning C26402

Return a scoped object instead of a heap-allocated if it has a move constructor (r.3).

Remarks

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.

Example

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;
}