| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
原始链接: https://news.ycombinator.com/item?id=43999492
Hacker News上的一篇讨论集中在C++初始化的怪癖上,尤其关注未初始化变量可能导致的未定义行为(UB)。许多评论者都认为C++的默认初始化行为是有问题的,可能导致难以调试的bug,尤其对于新手来说。 一些人提出了解决方案,例如默认初始化为零,或者要求使用明确的关键字来表示有意不初始化,优先考虑安全性而不是微小的性能提升。向后兼容性问题被提出,但一些人认为带有UB的旧代码本来就已经可以说是坏了。另一些人则抵制“训练轮”的想法,更倾向于程序员拥有最终的控制权,即使这意味着冒着UB的风险。他们还建议显式初始化是解决这个问题的方法。 讨论涉及到优化和安全之间的矛盾、C++初始化规则的复杂性以及该语言历史上对底层的关注。一些人指出,其他语言,如Rust,默认情况下更安全地处理初始化。C++在性能关键型环境(嵌入式系统)中的作用也被提及。
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
I've been using C++ for a decade. Of all the warts, they all pale in comparison to the default initialization behavior. After seeing thousands of bugs, the worst have essentially been caused by cascading surprises from initialization UB from newbies. The easiest, simplest fix is simply to default initialize with a value. That's what everyone expects anyway. Use Python mentality here. Make UB initialization an EXPLICIT choice with a keyword. If you want garbage in your variable and you think that's okay for a tiny performance improvement, then you should have to say it with a keyword. Don't just leave it up to some tiny invisible visual detail no one looks at when they skim code (the missing parens). It really is that easy for the language designers. When thinking about backward compatibility... keep in mind that the old code was arguably already broken. There's not a good reason to keep letting it compile. Add a flag for --unsafe-initialization-i-cause-trouble if you really want to keep it.
C++, I still love you. We're still friends.
reply