boostorg / boostorg/safe_numerics
Surprising Unitialized Variable detection
- Dominant language
- C++
- Stars
- 222
- Forks
- 46
- PR merge metrics
- No merged PRs in 30d
Description
The following code has UB due to reading a variable with indeterminate value:
```c++
int i; // no value assigned
std::cout << i;
```
However, the following code is perfectly correct:
```c++
int i; // no value assigned
std::cin >> i;
std::cout << i;
```
For this reason, I would expect the following code not to throw exceptions:
```c++
namespace sn = boost::safe_numerics;
using my_policy = sn::exception_policy<
sn::throw_exception,
sn::throw_exception,
sn::throw_exception,
sn::throw_exception // throw on uninitialized value
>;
template
using my_safe = sn::safe;
int main()
{
my_safe i; // this throws
std::cin >> i;
}
```
This is unfortunate, because the library throws for a perfectly valid code. My natural expectation would be that the my safe int will want me when I try to *read* the indeterminate value (rather than when one is produced).
With the current behavior, I am forced to put some starting value that will be discarded the moment after. I consider it a bad programming practice, despite what many teachers say, as explained in these blog posts:
* [Concealing bugs](https://akrzemi1.wordpress.com/2016/12/12/concealing-bugs/),
* [Treating symptoms instead of the cause](https://akrzemi1.wordpress.com/2018/11/22/treating-symptoms-instead-of-the-cause/).
I imagine that detecting the read of indeterminate value is more difficult to implement, because you have to keep the track of the variable initialization state in a separate variable. If this is unimplementable, at mnimum, I would expect the documentation to warn me about the current, somewhat surprising behavior.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.