llvm / llvm/llvm-project

[clang-tidy] New check: modernize-use-shared-ptr-array

Open
#180,441 2 comments 0 reactions 1 assignee Claimed by @Shriya-Tyagi View on GitHub
check-request clang-tidy
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

### Motivation

With C++17, `std::shared_ptr` gained proper array support through the specialization `std::shared_ptr`. This provides:
- Type safety: Clear indication that the pointer owns an array
- Simplified syntax: No need for custom deleters
- Standard compliance: Uses standardized array deletion
- Readability: Intent is immediately clear from the type

In old C++ versions developers must use workarounds like:
```cpp
// Pre-C++17 workarounds
std::shared_ptr sp1(new A[10], std::default_delete());
std::shared_ptr
sp2(new A[10], [](A* p) { delete[] p; });
```

These can be modernized to:
```cpp
// C++17 and later
std::shared_ptr sp(new A[10]);
```

### Scope

The check would identify and transform:
- `std::shared_ptr` constructed with `new T[N]` and `std::default_delete`
- `std::shared_ptr` constructed with `new T[N]` and a lambda deleter containing `delete[]`

### Implementation Approach

The check would:
1. **Match patterns** using Clang AST matchers for:
- `std::shared_ptr` constructors with two arguments
- First argument: `new T[N]` expression
- Second argument: Custom deleter (default_delete or lambda)

2. **Verify deleter semantics**:
- For `std::default_delete`: Confirm template argument is array type
- For lambdas: Analyze body for `delete[]` statement
- For other callables: Attempt to determine if they perform array deletion

3. **Apply transformation**:
- Change `shared_ptr` to `shared_ptr`
- Remove custom deleter argument
- Preserve any explicit template arguments or qualifications

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.