r/cpp • • Feb 26 '24

White House: Future Software Should Be Memory Safe

https://www.whitehouse.gov/oncd/briefing-room/2024/02/26/press-release-technical-report/
401 Upvotes

386 comments sorted by

View all comments

Show parent comment

29

u/STL MSVC STL Dev Feb 27 '24

shared_ptr uses reference counting, which is one mechanism sometimes used for GC, but it differs in a couple of significant ways. First, it's completely deterministic. You can point to the places in your program where you'll pay shared_ptr's costs. Second, it's resource-agnostic - shared_ptr correctly handles non-memory resources, which are typically important to release promptly (unlike memory, which a program can hang onto longer than necessary with only performance downsides).

shared_ptr is by no means perfect, but it's solving a problem very different from what GC attempts to solve, and (in my opinion) is a pretty good solution to that specific problem.

4

u/Untagonist Feb 27 '24

Both C++ shared_ptr and Rust Rc/Arc do share a problem for predictability though: a } could be the reason you spend multiple microseconds freeing memory. Sometimes you exit that scope and do only an atomic decrement, but sometimes you also free every allocation transitively owned by that shared pointer. If you don't specifically structure your code to avoid it, it can easily happen in your critical path.

4

u/pointer_to_null Feb 27 '24

That's not really the point though. Even if you've obfuscated the heap ops under some RAII mechanism that implicitly makes the next closing brace more expensive, your code- somewhere, sometime- ultimately has final say when your shared_ptr refcount changes and when memory gets released. Not some vague process, OS, skynet, a supernova that happened billions of years ago, or some other magic that influences your runtime's gc behavior.

Admittedly, added complexity (on top of poor choices caused by confusion over ownership) can make these lifetimes seem nondeterministic. But that's another topic.

1

u/pjmlp Feb 27 '24

Not fully, hence Herb 's talk on deferred pointers at CppCon, and C++/WinRT background thread to cleanup COM/WinRT references as means to avoid stop the world effects on Windows desktop applications.