4 ms·
Just one or two days ago I asked here on HN how memory allocations in C++ are considered to be more hidden than in Rust and got some good replies: Especially co
by dthul 6y ago
Just one or two days ago I asked here on HN how memory allocations in C++ are considered to be more hidden than in Rust and got some good replies: Especially constructors, copy constructors, assignment operators etc. can introduce non-obvious allocations.
For example:
T t;
a = b;
T t2 = t;
can all allocate in C++. The equivalent in Rust:
let t: T; // won't allocate
let t = T::new(); // might allocate
a = b; // won't allocate
let t2 = t; // won't allocate
let t2 = t.clone(); // might allocate
So in Rust you can tell that as long as there is no function call, there won't be an allocation.
- pjmlp 6y agoLike operator overloading and implicit conversations.
- dthul 6y agoTrue, those are even more places where C++ can implicitly allocate. The operator overloading also applies to Rust. Rust has no implicit conversions though, which are arguably worse since they are invisible (that's why I usually mark all my expensive single argument constructors as "explicit").
- pjmlp 6y agoSure it has, you cannot ensure Deref implementations don't allocate.
- dthul 6y agoWhile technically true, the documentation makes it very clear that Deref should only be implemented for smart pointers and never fail. So no allocations in practice.
- pjmlp 6y agoAh problem solved then, we just need to document very clear that C code should not corrupt memory, how did I never thought of it.