Skip to content

Commit 0b95999

Browse files
author
Colin Robertson
authored
Merge pull request MicrosoftDocs#2404 from JordanMaples/patch-24
Add example for C26402
2 parents c9741f7 + 0eda69d commit 0b95999

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

docs/code-quality/c26402.md

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,44 @@
11
---
22
title: C26402
3-
ms.date: 09/04/2019
3+
ms.date: 08/20/2020
44
ms.topic: "conceptual"
55
f1_keywords: ["C26402"]
66
helpviewer_keywords: ["C26402"]
77
ms.assetid: b9d3d398-697a-4a5d-8bfe-9c667dffb90b
88
---
99
# C26402 DONT_HEAP_ALLOCATE_MOVABLE_RESULT
1010

11-
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.*
11+
> `Return a scoped object instead of a heap-allocated if it has a move constructor (r.3).`
12+
13+
## Remarks
14+
15+
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](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.*
16+
17+
## Example
18+
19+
This example shows a function, `bad_example`, that raises warning C26409. It also shows how function `good_example` doesn't cause this issue.
20+
21+
```cpp
22+
// C26402.cpp
23+
24+
struct S
25+
{
26+
S() = default;
27+
S(S&& s) = default;
28+
};
29+
30+
S* bad_example()
31+
{
32+
S* s = new S(); // C26409, avoid explicitly calling new.
33+
// ...
34+
return s; // C26402
35+
}
36+
37+
// Prefer returning objects with move contructors by value instead of unnecessarily heap-allocating the object.
38+
S good_example() noexcept
39+
{
40+
S s;
41+
// ...
42+
return s;
43+
}
44+
```

0 commit comments

Comments
 (0)