[LifetimeSafety] `-Wlifetime-safety-invalidation`: false positive when using a `unique_ptr` after `reset()`
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
`$ cat test.cpp`
```c++
#include
void true_positive(std::unique_ptr &p) {
int *raw = p.get(); // expected: "parameter 'p' is later invalidated"
p.reset();
(void)*raw; // use of dangling pointer
}
bool false_positive(std::unique_ptr &p, int *new_val) {
p.reset(new_val);
return static_cast(p); // spurious: "parameter 'p' is later invalidated"
}
```
```console
$ clang++ -fsyntax-only -std=c++17 -Wlifetime-safety-invalidation test.cpp
test.cpp:3:20: warning: parameter 'p' is later invalidated [-Wlifetime-safety-invalidation]
3 | void true_positive(std::unique_ptr &p) {
| ^~~~~~~~~~~~~~~~~~~~~~~
test.cpp:5:5: note: parameter 'p' is invalidated here
5 | p.reset();
| ~~^~~~~~~
test.cpp:6:10: note: later used here
6 | (void)*raw; // use of dangling pointer
| ^~~
test.cpp:9:21: warning: parameter 'p' is later invalidated [-Wlifetime-safety-invalidation]
9 | bool false_positive(std::unique_ptr &p, int *new_val) {
| ^~~~~~~~~~~~~~~~~~~~~~~
test.cpp:10:5: note: parameter 'p' is invalidated here
10 | p.reset(new_val);
| ~~^~~~~~~~~~~~~~
test.cpp:11:28: note: later used here
11 | return static_cast(p); // spurious: "parameter 'p' is later invalidated"
| ^
2 warnings generated.
```
This looks like a false positive. `unique_ptr::reset()` invalidates raw pointers previously obtained via `get()`, not the `unique_ptr` object itself.
Introduced by #194907.
Contributor guide
Research direction
Reproduce the diagnostic with the supplied test.cpp and the clang++ command using -Wlifetime-safety-invalidation. Trace the warning’s handling of unique_ptr::reset() and compare the true_positive and false_positive cases. Done means the true positive still warns while using the unique_ptr after reset(new_val) no longer produces a spurious warning.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 64/100