Introduce `not_null` and a safe `std::optional` to avoid dereferencing nullptrs
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 1k
- Forks
- 423
- Avg merge
- 1d 15h
- Merged PRs (30d)
- 24
Description
Enhancement
Currently, codes are prone to panic / UB if:
- We derefing an
std::shared_ptrof nullptr. - We derefing an
std::optionalof nullopt.
For example
#include <optional>
#include <cstring>
#include <cstdio>
#include <memory>
struct I {
int get() { return 1; }
};
void f() {
try {
std::optional<std::shared_ptr<I>> x = std::nullopt;
printf("%d\n", (*x)->get()); // -----> UB, and returns wrong result rather than panic on g++
}
catch (std::bad_optional_access & e) {
printf("it throws in f\n");
}
}
void g() {
try {
int * x = nullptr;
printf("%d\n", *x); // -----> UB and panics
} catch (...){
printf("it throws in g\n");
}
}
If these happens, it will be segment fault, and it is very hard to find what causes the panic. https://github.com/pingcap/tiflash/issues/8249 is an example. It is also not worthy to check by if everytime we try to deref. For example, if the API provider always returns a valid ptr, it can use not_null.
So I suggest we introduce not_null and safe_option in TiFlash.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the issue's null-dereference examples, the linked Microsoft GSL not_null implementation, and the linked safe_option proposal. Clarify the desired APIs, ownership and failure behavior with maintainers; done requires an agreed scope and validation for both shared-pointer and optional cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100