3 ms·
> I don't understand the obsession with constructors. The article describes how smart pointers are more difficult to use for opaque/POD structs without destruc
by nyanpasu64 5y ago
> I don't understand the obsession with constructors.
The article describes how smart pointers are more difficult to use for opaque/POD structs without destructors. Correct me if I'm wrong, but I think types with destructors generally require constructors too (though you can sometimes rely on default destructors/constructors, by holding fields which themselves have destructors/constructors).
> Fallible placement initialisation into allocated memory is something that I honestly don't know a good use case for. It's certainly not something that's very common and I never encountered it.
Understandable. Rust lacks any safe means for placement initialization (even infallible), resulting in stack overflows (often disappearing in optimized release builds) when allocating large heap arrays (because it has to stack-allocate the array, then memcpy to the heap), eg. https://github.com/rust-lang/rust/issues/53827 https://github.com/rust-lang/rust/issues/53827. I haven't encountered this firsthand though.
> It also again boils down to a case of premature optimisation
Copying can be a correctness issue as well as performance. One time I wrote a function which took an object by copy (when I should've passed by reference), and returned a reference to the object, resulting in a use-after-free. Additionally mutating a copy doesn't mutate the original object, unlike a non-const reference.
- qayxc 5y ago> I think types with destructors generally require constructors too If by that you mean explicit constructors, then no. The compiler will happily generate an empty default ctor for you. Ctors in general are only useful to establish a known initial state and uphold class invariants. If neither of these applies (e.g. no class invariant or delayed initialisation), no ctor is necessary (or even wanted for that matter - initialisation is not free). > Copying can be a correctness issue as well as performance. Agreed, but that is just a matter of language semantics. Take the opposite for example: in Java every non-primitive is passed by reference. You get the opposite problem and now have to deal with (sometimes implicitly) boxed values and cumbersome cloning-interfaces. C++ has references and (const-) pointers and it's the programmer who decides when to use which option. The language itself doesn't limit or restrict the programmer in that regard and unlike Java it's more consistent in its semantics (i.e. no ominous "value types" that require boxing and are not passed by reference).