Skip to content

Commit fbb20ea

Browse files
authored
Add example for C26402
1 parent c9741f7 commit fbb20ea

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

docs/code-quality/c26402.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,27 @@ ms.assetid: b9d3d398-697a-4a5d-8bfe-9c667dffb90b
99
# C26402 DONT_HEAP_ALLOCATE_MOVABLE_RESULT
1010

1111
To avoid confusion about whether a pointer owns an object, a function that returns a movable object should allocate it on the stack and return it by value instead of returning a heap-allocated object. If pointer semantics are required, then return a smart pointer instead of a raw pointer. See [C++ Core Guidelines R.3](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-ptr): *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.*
12+
13+
# Example
14+
```cpp
15+
struct S
16+
{
17+
S() = default;
18+
S(S&& s) = default;
19+
};
20+
21+
S* foo()
22+
{
23+
S* s = new S(); // C26409, avoid explicitly calling new.
24+
// ...
25+
return s; // C26402
26+
}
27+
28+
// Prefer returning objects with move contructors by value instead of unnecessarily heap-allocating the object.
29+
S bar()
30+
{
31+
S s;
32+
// ...
33+
return s;
34+
}
35+
```

0 commit comments

Comments
 (0)