llvm / llvm/llvm-project

[libc++] std::out_ptr parameter not set if reused within full-expression

Open
#216,385 2 comments 0 reactions 0 assignees View on GitHub
libc++
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Consider the following snippet:

```c++
#include
#include

bool TryCreate(int** ptr) {
*ptr = new int(123);
return true;
}

int main() {
std::unique_ptr foo;
if (!TryCreate(std::out_ptr(foo)) || !foo) {
std::cout << "foo is nullptr\n";
} else {
std::cout << "foo is valid\n";
}
}
```

In libc++, `std::out_ptr(foo)` keeps a reference on `foo`, but hands over a separate raw pointer to `TryCreate`. `foo` is only [assigned in `~out_ptr_t()`](https://github.com/llvm/llvm-project/blob/9223dc8b71d11798656fc5fbac507118881632bc/libcxx/include/__memory/out_ptr.h#L56-L71). This means that if `foo` is re-used within the same full-expression, it will not hold the current updated value. In the example above, the program would output "foo is nullptr".

libstdc++ on the other hand directly gives `TryCreate` a pointer into the internals of `std::unique_ptr`, meaning that `foo` gets directly assigned by `TryCreate`. With libstdc++, the above program outputs "foo is valid".

See this in action here: https://godbolt.org/z/GsoKszbnq

The approach used by libstdc++ is more efficient because it doesn't need to use a separate variable, but it's also safer because it can prevent subtle bugs caused by the delayed smart pointer initialization.

Can libc++ be updated to behave similarly to libstdc++? If not, could this usage pattern be detected by clang-tidy?

Contributor guide

Open the contributing guide

Research direction

Reproduce the example using the linked Godbolt case, then read libcxx/include/__memory/out_ptr.h, especially the out_ptr_t destructor and assignment path. Compare the observed reuse behavior with the libstdc++ behavior described in the issue, and determine whether libc++ behavior or a clang-tidy diagnostic is the appropriate resolution, with regression coverage for the chosen outcome.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.