3 ms·
1) Using smart pointers makes it really hard to have dangling pointers. 2) The invalidation rules are pretty well known at this point, but I concede that it's
by blub 11y ago
1) Using smart pointers makes it really hard to have dangling pointers.
2) The invalidation rules are pretty well known at this point, but I concede that it's much better to have compile-time validation. A good STL impl will have iterator debugging, which catches iterator invalidation. e.g: debug mode in GCC
3) Regarding null, you're theoretically right, undefined behaviour and all. In practice[1], accessing a null pointer/reference will result in a crash both in C# and C++.
When developing Java apps (C#'s big brother), the biggest sources of bugs during development were null pointer exceptions and unhandled exceptions propagating to the event loop and killing the UI thread.
[1] There are strange cases such as http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html?m=1 http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
- pcwalton 11y ago> Using smart pointers makes it really hard to have dangling pointers. No, it doesn't. std::vector<std::unique_ptr<int>> x; x.push_back(std::make_unique(1)); auto& y = *x[0]; x.clear(); std::cout << y; // use after free This is, of course, a toy example. For lots and lots of real examples, search Web browser engine bug trackers for UAF vulnerabilities. (They have been using smart pointers exclusively for a decade or so now.) > A good STL impl will have iterator debugging, which catches iterator invalidation. Valgrind and ASan catch UAF too and have been around for years and years. Yet we still have a ton of UAF vulnerabilities.
- blub 11y agoWith C++ one needs discipline to make up for the lack of type safety that one can get in other languages. This is of course not so great, because it relies on the programmer to know various idioms/patterns. In your example, it would be a major red flag in code review to create a reference like that. Some code constructs are just asking for trouble. I think the reasons behind still having errors despite tools like Valgrind and ASan are: a) many devs don't know about them or use them b) you need 100% coverage to remove all errors Using said engineering practices will not result in a completely big-free program, but it will have a significant impact on the quality. For something that doesn't have the nightmare security profile of a browser or various other exposed services, that can be just fine, even if not ideal.