←back to thread

In Defense of C++

(dayvster.com)
185 points todsacerdoti | 1 comments | | HN request time: 0s | 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. deschutes ◴[] No.45272386{3}[source]
You are correct, it does not affect the lifetime of the pointed object (pointee).

But a shared_ptr manages at least 3 things: control block lifetime, pointee lifetime, and the lifetime of the underlying storage. The weak pointer shares ownership of the control block but not the pointee. As I understand this is because the weak_ptr needs to modify the control block to try and lock the pointer and to do so it must ensure the control block's lifetime has not ended. (It manages the control blocks lifetime by maintaining a weak count in the control block but that is not really why it shares ownership.)

As a bonus trivia, make_shared uses a single allocation for both the control block and the owned object's storage. In this case weak pointers share ownership of the allocation for the pointee in addition to the control block itself. This is viewed as an optimization except in the case where weak pointers may significantly outlive the pointee and you think the "leaked" memory is significant.