Skip to content

Commit fe10f14

Browse files
author
Colin Robertson
authored
Merge pull request MicrosoftDocs#2651 from Xazax-hun/patch-2
Clarify behavior of C26409 for delete this idiom
2 parents a0f224c + ab06caf commit fe10f14

1 file changed

Lines changed: 25 additions & 4 deletions

File tree

docs/code-quality/c26409.md

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
2-
description: "Learn more about: C26409 NO_NEW_DELETE"
2+
description: "Learn more about CppCoreCheck rule C26409: avoid explicit new and delete."
33
title: C26409
4-
ms.date: 08/20/2020
4+
ms.date: 12/14/2020
55
ms.topic: "conceptual"
66
f1_keywords: ["C26409"]
77
helpviewer_keywords: ["C26409"]
@@ -11,7 +11,7 @@ ms.assetid: a3b3a229-d566-4be3-bd28-2876ccc8dc37
1111

1212
> `Avoid calling new and delete explicitly, use std::make_unique<T> instead (r.11).`
1313
14-
Even if code is clean of calls to`malloc()` and `free()`, we still suggest that you consider better options than explicit use of operators [`new` and `delete`](../cpp/new-and-delete-operators.md).
14+
Even if code is clean of calls to `malloc` and `free`, we still suggest that you consider better options than explicit use of operators [`new` and `delete`](../cpp/new-and-delete-operators.md).
1515

1616
**C++ Core Guidelines**:\
1717
[R.11: Avoid calling new and delete explicitly](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly)
@@ -22,7 +22,7 @@ The ultimate fix is to use smart pointers and appropriate factory functions, suc
2222

2323
- The checker warns on calls to any kind of operator **`new`** or **`delete`**: scalar, vector, overloaded versions (global and class-specific), and placement versions. The placement **`new`** case may require some clarifications in the Core Guidelines for suggested fixes, and may be omitted in the future.
2424

25-
## Example
25+
## Examples
2626

2727
This example shows C26409 is raised for explicit **`new`** and **`delete`**. Consider using smart pointer factory functions such as `std::make_unique` instead.
2828

@@ -35,3 +35,24 @@ void f(int i)
3535
auto unique = std::make_unique<int[]>(i); // prefer using smart pointers over new and delete
3636
}
3737
```
38+
39+
There's a C++ idiom, `delete this`, that triggers this warning. The warning is intentional, because the C++ Core Guidelines discourage this pattern. You can suppress the warning by using the `gsl::suppress` attribute, as shown in this example:
40+
41+
```cpp
42+
class MyReferenceCountingObject final
43+
{
44+
public:
45+
void AddRef();
46+
void Release() noexcept
47+
{
48+
ref_count_--;
49+
if (ref_count_ == 0)
50+
{
51+
[[gsl::suppress(i.11)]]
52+
delete this;
53+
}
54+
}
55+
private:
56+
unsigned int ref_count_{1};
57+
};
58+
```

0 commit comments

Comments
 (0)