←back to thread

In Defense of C++

(dayvster.com)
185 points todsacerdoti | 1 comments | | HN request time: 0.244s | source
Show context
nzeid ◴[] No.45268229[source]
> Just using Rust will not magically make your application safe; it will just make it a lot harder to have memory leaks or safety issues.

You know, not sure I even agree with the memory leaks part. If you define a memory leak very narrowly as forgetting to free a pointer, this is correct. But in my experience working with many languages including C/C++, forgotten pointers are almost never the problem. You're gonna be dealing with issues involving "peaky" memory usage e.g. erroneously persistent references to objects or bursty memory allocation patterns. And these occur in all languages.

replies(4): >>45268599 #>>45268701 #>>45268705 #>>45270660 #
AlotOfReading ◴[] No.45268701[source]
C++'s design encourages that kind of allocation "leak" though. The article suggests using smart pointers, so let's take an example from there and mix make_shared with weak_ptr. Congrats, you've now extended the lifetime of the allocation to whatever the lifetime of your weak pointer is.

Rc::Weak does the same thing in Rust, but I rarely see anyone use it.

replies(2): >>45271718 #>>45274602 #
fluoridation ◴[] No.45271718[source]
Huh? What do you mean? The point of std::weak_ptr is that it's non-owning, so it has no effect on the lifetime of the pointed object.
replies(2): >>45272386 #>>45272394 #
1. AlotOfReading ◴[] No.45272394[source]
It has no effect on the lifetime of the object, but it can affect the lifetime of the allocation. The reason is that weak_ptr needs the control block, which make_shared bundles into the same allocation as the object for optimization reasons.

Quoting cppreference [0]:

    If any std::weak_ptr references the control block created by std::make_shared after the lifetime of all shared owners ended, the memory occupied by T persists until all weak owners get destroyed as well, which may be undesirable if sizeof(T) is large.
[0] https://en.cppreference.com/w/cpp/memory/shared_ptr/make_sha...