Constructors are such an odd duck to me. On the one hand, you have languages like C++ and Swift which have construction as a first-class concept, with tons of rules you need to memorize (Swift's "convenience" vs "designated" initializers are a real treat to unpack).
Then you have languages like Rust, Go, Zig, etc which don't have them at all, constructors are just static functions in the namespace of the type, which return an instance of that type.
For the life of me I've never understood why you'd want the former. I'm sure there's a reason, but I never miss it when using languages in the latter category.
The explanation you typically hear is about OO and inheritance, but I don't buy it: If Animal had a ::new() that initialized private state, Cow could have a ::new() too that could call Animal::new() if it wanted, then do further initialization, etc... I don't think there's anything about inheritance that says constructors are a must. (Edit: In fact, ObjC does exactly this. I should have remembered that given that I did ObjC for a living for a while.)
Because in languages like C++ and Swift, contrary to your other examples, the goal is that library types should be able to do everything that built-in types expose.
Thus you need all mechanisms to implement the same capabilities, thus constructors, by the way they are not alone in this approach.
In C++ you can write "int x;" and get an object of type int.
If the only way to initialise a class-type object was to call some custom static method on it then you'd have to write "Foo x = Foo::create();". Suddenly it looks more special than a built-in type.
In C++, `int x;` leaves the int uninitialized, which isn't really constructing at all. In rust (which I program in lately so I'll use it as the example) you simply can't use uninitialized variables in the first place without unsafe code, so the equivalent would either be:
let x: i32;
foo(x); // compiler error
or if you really wanted to use uninitialized memory,
which, in rust, can be done with any other type too (substitute i32 for any T and the above examples are identical.) I don't see anything different about built-in types here vs standard ones, other than the compiler has literals for the built-ins, which is more a consequence of rust not allowing literals for library types. But that's a very different discussion.
I guess the argument might be that for C++, they want the author of the type to determine whether the value should be left uninitialized on declaration/construction, instead of the caller. Which is... not exactly the semantics I would have chosen.
Hmm interesting. Is there a way to "value initialise" (in C++ speak) an int in Rust to set it to zero? Like `let x: i32 = {};` (without explicitly writing `=0`)? How about a way to do that for a sort of plain struct where there are multiple members you just want to set to their default values?
Please note that mem::uninitialized is always unsound. Your example should be using MaybeUninit<T>. While that example would still be unsound directly anyway, it at least gives you the ability to do the right thing (foo would need to take the MaybeUninit<i32>).
As I replied in a sibling comment to yours, at least one language without constructors (Rust) has the exact same semantics for built-in types vs library types here. You must initialize in typical code, and the escape hatch is std::mem::uninitialized() which lets you work with uninitialized data, and this is true for any type, built-in or otherwise.
For many years now, This function is deprecated. Use MaybeUninit<T> instead.
core::mem::uninitialized is of course unsafe, but what people who designed it hadn't really appreciated was that in most cases it was impossible to use it correctly, it almost might as well have been a call to core::hint::unreachable_unchecked
If your type is a ZST then core::mem::uninitialized was safe to use, because not initializing zero bytes of RAM is the same as initializing all zero of them, this can't possibly matter so we're fine. Otherwise though, we create values which the LLVM backend is sure we cannot know and so it feels entitled to optimise as if any assumptions we make about those values are false, even if the results are contradictory. This causes immediate Undefined Behaviour all over the place.
The MaybeUninit<T> wrapper type is pretty easy to use and won't invoke Undefined Behaviour so long as you do everything in the instructions.
That feels a bit like begging the question? Library types only need constructors to replicate built-in types if built-in types use constructors themselves. But do built-in types need constructors? What is lost by just using regular functions?
Also I was under impression that Rust at least has a similar goal?
Both those feel a bit like circular arguments? They need constructors because that's how they are currently defined, but that doesn't say anything about whether they could also be defined without constructors.
The latter was what I was interested in, and I apologize for not making that clear. For instance, in Rust terms both those seem replaceable in principle via calls to appropriate trait functions like Default::default() or From::from().
> Also I was under impression that Rust at least has a similar goal?
Rust's choice here is slightly different, Rust wants to give all of the types features, whereas C++ wanted to specifically give the user defined classes as much functionality as possible.
So in Rust 5 and "Five" and '5' and [5, 5, 5, 5, 5] all can have the features you get in your own custom type named Five whereas in C++ they do not. In C++ they're not allowed to have methods ("member functions") because they are "just" primitive types. In Rust the operators are actually implemented for all the types they can be used on, not just for your own user defined classes and so on.
In a few cases this is "fake", for your own type to have a + operator you'd have to write an implementation of addition and the Rust stdlib provides an "implementation" for the machine integers which says nothing of importance because of course in reality that code is never executed, the Rust compiler knew how to add two integers together already. However most of them are real albeit often trivial.
Because Rust doesn't privilege a specific user defined type, all the user defined types get the features which make sense, including not only struct but also enum and union. It still surprises me that C++ never gave enum class (its improvement on the C enum user defined type) methods, of course a Rust enum has methods.
For ergonomics in the general case, I agree that it's not even a question, the Rust/Zig create-and-return approach wins on every count.
However, create-and-return makes in place construction difficult. C++ allows you to construct directly into any pinned memory block with satisfactory size and alignment, whereas create-and-return requires you to construct elsewhere and then copy the bytes. This has downstream implications:
- The address of "this" always changes at least once, which makes self-referential data structures and cyclic data structures more difficult. Now you have a pointer fixup step, or you are passing around some form of handle rather than raw pointers. These solutions can range from trivial to complicated, fast to slow, depending on the specific patterns in your code base. A simpler work around is to always construct with a fresh heap allocation and return a pointer to it, which, again, may or may not be an acceptably performant solution for your particular problem.
- You have to rely on your optimizer to do copy elision, which is not a guarantee. Not an issue for small objects, but it can become an issue for larger ones or for many repeated constructions.
But C++ has the return value optimisation (even the named return value optimisation), where you construct an object in a function and then "return" it, but it's actually constructed in place at the call site (not guaranteed but allowed by the language and widely implemented):
I don't know enough about Rust to know whether it has the same thing, but surely it could? If anything, it feels like it ought to be easier (for the compiler) because Rust moves rather than copies by default, and moves are destructive and bytewise.
Given that, it seems like a language could be designed so that a static method that returns an object could be allowed to construct an object in place. Again, I don't know enough about Rust or Zig to know if that's true of them.
Rust doesn't really have a good answer for guaranteed copy elision or in-place initialization at the moment. The devs are working on it, though (https://github.com/rust-lang/rust/issues/153825).
right, first-class support for a special say "must_construct_inplace" keyword on a function returning an object would be an interesting language design direction...
What happens inside
must_construct_inplace Foo make_foo() { ... }
can be as "inefficient" as your example above, but the compiler would validate & figure out a way to make it an in-place-construction, guaranteed RVO.
(similar to `constexpr` validation)
EDIT: Looks like this already exists under several names ("build-in-place", "placement by return", "result location semantics") in Ada's `return W : Widget do ... end return;`, Carbon's returned var c: Circle; ... return var;`, and Rust has (still open) RFC 2884 "placement by return", and Zig seems to have this fully built-in via result location semantics?!
RVO helps, but it is not necessarily enough. Let's say you have a vector and you want to construct in-place an element with an arbitrary set of arguments.
In c++ this is solved[1] via 1) emplace_back 2) perfect forwarding 3) constructors having an homogeneous name and being selected via overload resolution.
In a language with RVO, it is not enough for 'make_foo' in 'push_back(make_foo(args...))' to guarantee zero copy, 'push_back(x)' must also be able to guarantee that its parameter x is somehow constructed in place.
In practice you need some form of lazy evaluation (call by name, or an explicit thunk or passing the function and parameters separately) or some form of macro expansion.
[1] it does comes with its own set of foot-bazookas of course.
> not guaranteed but allowed by the language and widely implemented
Ome can make it guaranteed (assuming Foo is an aggregate) by writing:
Foo make_foo() {
return Foo{.blah = 7};
}
This guarantees initialization happens at the end of the function, since you are returning a pure rvalue. Generally a good style rule to adopt and no annotations needed.
Agree. C++17 lets you write factory functions that directly return `T(args...)` and can initialize an `auto foo = make_t();` so in many cases the distinction between rust and modern c++ is diminished.
But still, doing `std::make_unique<T>(args...)` or allocates storage and guarantees to run T's constructor there, and you can even do `std::optional<std::mutex> slot; slot.emplace();` which builds the mutex inside the optional even though a std mutex can't be moved or copied.
> However, create-and-return makes in place construction difficult
This is definitely the closest thing to an answer in this thread. This is something that languages without constructors do struggle with, yes, and as other commenters pointed out, Rust sees this as a performance issue and is working on it.
It's a tradeoff thing. In languages like C and Zig you can declare a struct (which, naturally, will start out containing whatever random garbage was at that memory location) and then just begin assigning values to its fields.
But in C++ and Rust, assignment itself is a method which can be overridden. So what does it mean to call a method on an object that doesn't exist yet? Also, destructors have to be run when an object goes out of scope. But what if an error occurs before all the fields have been assigned - now you're destructing objects that don't semantically exist yet, and whose memory contains garbage.
That's why I say it's a trade-off - if they wanted, the designers of C++ and Rust certainly could have just allowed programmers to paint themselves into such corners. But they preferred to disallow these things entirely and instead require objects to be constructed all at once as a semantic unit.
To clarify, Rust doesn't allow overloading the assignment operator. The compound arithmetic assignment operators like `+=` are overridable, but that doesn't pose any problem for the use-before-init analysis, which already prevents all methods from being called on uninitialized variables.
As you say C++ needs constructors that are not ordinary functions for things like in-place construction.
However this is a very bad and unnecessary hack, which I consider as the worst mistake of C++ (already present in the first "C with Classes", before becoming C++).
The correct solution is to distinguish output parameters from input-output parameters, like e.g. in Ada.
The difference is that an input-output parameter contains memory on which some object has already been constructed before invoking the function, while an output parameter contains uninitialized memory upon function entry.
In a language that has 3 parameter types (input, output and input-output), constructors are just ordinary functions that have an output parameter of the type that is constructed. No special treatment for constructors is needed.
When defining classes, one would have to optionally specify only a default constructor and a destructor, because these must be invoked implicitly by the compiler. Any explicit initialization of an object would use arbitrary functions with suitable parameter types.
The result parameter of a function should be an output parameter. If an already existing object is passed as an output parameter to a function, inclusively for its result parameter, the compiler would invoke implicitly the destructor for that class, before invoking the function.
Both output parameters and input-output parameters may be passed either by value or by reference, based on compiler or on ABI choices that are appropriate for their types.
When output parameters are passed by value, in registers, the compiler will store an output parameter from its register to the desired location, after the function returns, while when input-output parameters are passed by value, in registers, the compiler will load those registers before invoking the function and store them after the function returns.
I feel like this is leaving out the option of only ever referring to objects by a pointer. this means there's no shenanigans around moving or copying things around, and language semantics can still enforce single owners etc. The main disadvantage to this is that it makes any copying explicit, and introduces some (IMO fairly minor) sharp edges around accidentally modifying objects passed into functions etc.
One is that C++ has constructors, with lots of rules about which one is called when.
But the other is that primitive objects can sometimes be uninitialised, and sometimes that's what you want for performance (if you're about to overwrite them anyway). C++ classes are meant to be able to do anything a primitive type can (as a sibling comment says) so you sometimes want a class that you can either leave uninitialised or value initialise (essentially, set everything to zero) decided at the call site (not in the class declaration).
If C++ guaranteed that all members always had to be initialised, then all the default-like constructors (Foo x; Foo x = {}; Foo x = Foo(); etc) would resolve to the same thing (a call to the constructor you explicitly wrote if you did; otherwise all members default constructed, resolved as zero-initialisation if that's equivalent).
First of all, there is a question of syntax, which ironically could be solved by taking a page out of BCPL's book (the irony is that BCPL is C's ancestor, but C lost several of its more advanced features, like statement expressions):
double m[1024 * 1024] = ?;
Foo x = ?;
Second, there is a question of semantics. You only get to have 1 destructor, and it's called unconditionally — so we force the author of Foo (or of any class, really) to either 1) write the destructor that can properly destruct an unitialized object which is a bit tricky since reading any of the fields of such an object is UB; 2) shift the blame to the users: "don't do that with this class" — which completely negates your "decided at the call site (not in the class declaration)" point, because this decision is made in the class declaration, and can be made only there, not at the call site.
So as usual with C++, we end up with a half-working system, with subtle footguns, pervading all of the program code, and impossible to ignore.
The thing you are annoyed about in C++ is not constructors. It's the overloading of syntactic operations.
The C++ design bets heavily on that. Just like you can overload an operator, you can also overload the meaning of `=`, `new`, variable declarations, and etc. That necessarily leads to an awful complex language, but also a very powerful one that can potentially lead to very easy to read code in high abstraction levels.
The problem both C++ and Swift have is that you can't really build high abstraction levels, because the languages are designed in a way that makes some fixed concerns creep over your entire code.
I get that for C++ to have all this overloading it needs constructors, but Swift doesn't take the same bet as C++ does when it comes to overloading, yet it still has first-class constructors anyway. So do lots of other languages (Java, C#, TypeScript, etc.) Swift is especially interesting because it's basically a successor language to Objective-C, and Objective-C did not have first class constructors (`-init`/`-initWithFoo:` is just a convention), they chose to add it anyway.
The convenience vs. designated initialization in Swift is exactly the same kind of attempt to overload normal language syntax.
Outside of that, Swift has only normal OOP constructors, that are something completely different, and almost not a pain at all. Normal constructors are just a control layer on top of memory initialization that lets you write custom rules for it. It becomes necessary when you have protected memory in your objects, because the external code can't just go and set it, but even languages like Python understand it's convenient to have a defined place to set things up.
I was surprised reading these comments to see hardly any mention of type invariance, and no mention at all of RAII. RAII gets you type invariants that hold for the entire lifespan of an object, and if anything goes wrong during initialization, you are guaranteed to release all partial state according to its specified rules — giving you something closer to whole-program invariants. We all love POD / structs, but they don’t get you that part, and doing it without RAII can land anywhere from a bit of meticulous bookkeeping all the way to building an intractable metaprogramming malebolge just to get half-baked DIY RAII.
You don't really need C++-style constructors for RAII though. Rust implements similar semantics as C++ in that regard and constructors aren't a thing there.
Rust doesn’t have implementation inheritance. If it did, it would need some constructor-like concept as well to enforce encapsulation between inherited implementation and inheriting implementation.
Objective-C has implementation inheritance but doesn't have constructors, I don't think constructors are essential there. As I said in the OP, `Cow::new()` can easily just call `Animal::new()` before continuing to initialize its own fields, etc.
Heck, Smalltalk is the original OOP language and has implementation-based inheritance, and construction is done through ordinary methods on class objects.
Objective-C plays it fast and loose here. It doesn’t enforce object initialization, hence client code including subclasses can create and use uninitialized instances.
Smalltalk is even worse, but it also has the philosophy that anything can be patched at runtime, so it kind of is in line with that.
This is basically about static type safety.
You could in principle enforce proper initialization and encapsulation by static analysis requirements instead of by a dedicated language construct. The latter is traditionally more efficient however, and arguably makes the code more explicit about its intent.
Even if you assume that's true that seems more like "constructors are needed for implementation inheritance" than "constructors are needed for RAII".
I'm not even sure about the former? The important bit is that base class invariants can't be observed in an invalid/inconsistent state, and regular visibility/privacy/etc. rules seem technically sufficient for that? I'm not sure where exactly the boundaries of "constructor-like concept" are supposed to lie.
I'm not super familiar with Lua so just to make sure I'm understanding you correctly are you referring to to-be-closed variables?
If so, I think the difference is that in C++/Rust RAII is the default and is quite pervasive as a result. To-be-closed variables seem like IDisposable in C# or try-with-resources in Java in that they allow the programmer to use RAII-like semantics but are opt-in.
I usually need to use a Init() function to initialised the member functions, because they are initialised with data that isn't available when the constructor is called, making it largely redundant.
Another thing, just because a feature exists in a language doesn't mean you need to use it. Use it if it makes sense for your use case, otherwise don't use it.
Constructors make alot of sense to me. It's a promise to the caller that the instance is fully initialized after it returns.
But there are cases where it simply ain't possible. For exampIe I always struggle with object pools, where you construct a bare instance and reuse it later on. In such cases it is often very cumbersome to to guarantee that each instance is properly initialized and uninitialized in every case. It gets worse when different instances are involved, depending on each other. The more classes there are, the worse it gets.
The idea behind constructors is to preserve object's invariants (e.g. that a circle radius must be positive). In a language without constructor, if you initialize an object (allocate some memory and point to it) and only then fill its fields with some static function, it will contain potentially illegal state until you do.
The main idea is that the class in question establishes the invariants of the new instance through the constructor. Subclasses have no business to fudge anything about the invariants of the superclass, or to see the uninitialized state of the superclass instance (and possibly expose it to client code in that invalid state); same as any other client code. So an invocation order has to be enforced such that the superclass constructor is always called before the subclass constructor is executed with access to the superclass instance.
The whole idea of OOP, aside from inheritance, is that the class implementation controls and ensures the invariants of its instances, protecting their internal state from client code. This limits code that might accidentally leave the object in an invalid state to the class implementation. If the class implementation is correct, then the object can’t possibly get into an invalid state, because only the class implementation can manipulate that state. And, importantly, that encapsulation boundary also exists between superclass and subclass. Conceptually, from the perspective of the superclass, a subclass is client code just like any other client code, from which the internal state of the superclass instance has to be protected.
Hence there needs to be a concept of dedicated initialization functions to guarantee that instances are always properly constructed and client code outside the class can’t end up with a half-constructed object and/or see an object in uninitialized state. And with respect to a superclass, the code of a subclass is “outside the class”.
Rust allows establishing invariants on its types without having a designated "constructor" concept. It accomplishes the same with the equivalent of static methods. Constructors are simply unnecessary.
Two things make this possible, really: the first is that Rust doesn't have subclassing, so one classic reason for constructors doesn't exist. The second is Rust's privacy system, which makes it so that external users can be forbidden to use the literal syntax to create a struct. This is what lets you guard creation to preserve invariants.
One useful feature of constructors still doesn't exist, which would be the placement new style thing, but that's on its way as well, and is an optimization rather than a requirement for most cases.
Indeed. And forcing all object creation to be routed through the "constructor" concept leads to a whole host of problems. For example:
std::vector v("foo", "bar");
This should create a vector of two elements, right? Well, too bad; it crashes instead. Why? Because the inferred type is std::vector<char>, and it attempts to construct a vector from a pair of iterators. Why? Because the only way to distinguish between different modes of constructing an object is through overloading, and overloads are too often ambiguous.
Arthur O'Dwyer's crusade against CTAD (<https://quuxplusone.github.io/blog/tags/#class-template-argu...>) ultimately boils down to this problem, which is not really type deduction itself, but ambiguous overloads, which are hard to avoid when constructors are the only way to create an object, without resorting to clumsy workarounds like tag types (which create problems of their own).
There are other problems too, like the fact that you cannot call std::make_unique (or emplace) for a class with a private constructor even in a scope where you have access to the constructor itself.
Java absolutely does have the ambiguous overload problem.
public class MyVector {
public MyVector(int... items) {
System.out.println(String.format("constructing a vector of %d items", items.length));
}
public MyVector(int start, int end) {
System.out.println(String.format("constructing a vector from the range [%d, %d)", start, end));
}
}
How do you construct a MyVector of two items?
In JavaScript, how do you use new Array(...) to create an array consisting of a single integer? You can do the same with a single value of any other type.
The reason these languages don't have the make_unique or emplace problems is because they don't have a concept of in-place construction at all, since objects in those languages are heap-allocated and have reference semantics anyway.
Right, but that’s a relatively rare problem, and doesn’t usually result in crashes.
More importantly, you have exactly the same problem if you overload a regular method that way. So it’s a problem with overloading, not with constructors.
> How do you construct a MyVector of two items?
new MyVector(new int[] { 23, 42 })
The correct solution, of course, is to provide named static constructor methods instead (e.g. `MyVector.ofRange(start, end)`).
I do agree that support for named actual constructor methods would be nice. But they would still be constructors.
IIRC, one reason C++ uses overloading for all constructors is if the construction occurs in a template, the caller can select the constructors from outside by eg passing the correct arguments. If the constructor were named, there would be no way to pass in the name from outside the template.
I'm not praising C++ at all, but constructors serve as more than just a factory for the instances. The full comparison with Rust might be vs implementations of the Default, Into / From, Copy, and Clone traits in addition to ::new. (Maybe some others I missed too)
When I used to program in C++, my general rule was that applications follow the "rule of zero" (no explicit constructors), and libraries do what's needed to make the rule of zero work for applications.
You said it better than I did. What I tried to say (and failed) was that there's a style of C++ application code that doesn't need to do any of it: no constructors, assignments, or destructor. Sometimes library code needs those though.
30+ years ago it was easy to memorize all the rules for constructors, and much of the language itself. The improvements and additions over the years make it much harder.
I moved from C++ to Java in my career. I was immediatey struck by how much simpler was Java as a language, not limited to constructors. Can you believe that an entire blog post is required to explain this insanely nuanced part of C++? I don't miss the armory of footguns.
I think you can't get rid of constructors until you either get rid of object identity, or get rid of encapsulation. C never had encapsulation as a language feature, so it didn't need constructors, while Rust eliminated object identity - a value can be arbitrarily moved from one variable to another and there's no (safe) way to notice that happened.
But in C++ one variable is one object. When you write "mystruct foo;" a new mystruct is created at that point. That is a specific one that has a specific memory address and is not interchangeable with any other. If you wrote "mystruct foo = create_mystruct();" that would be kicking the can down the road because the mystruct that is returned by create_mystruct is not the same one as the variable foo, so you still need a constructor to initialize foo based on the result of create_mystruct before the result mystruct is destroyed. You could define it to be a bitwise copy but that wouldn't work for a lot of types (like string, or shared_ptr).
In a language like C, you define it as a bitwise copy and anything that becomes incorrect after a bitwise copy is left as an exercise to the programmer. In a language like Rust you have a strong ownership model that permits a bitwise move - which is the same as a copy, but the original is no longer considered an object, and won't have its destructor called, and the destination wasn't an object until it was copied into. This requires that the object doesn't hold a pointer to itself. In C++ you have neither and you have be able to call user-defined code here.
Later versions of C++ have something called RVO which actually allows the copy to be omitted but only in the specific case above. Other cases still need copies. The language is tortured to say that create_mystruct's return value isn't actually a separate temporary instance of mystruct but whatever goes in the return expression of create_mystruct is actually used to construct foo in the caller. Compilers implement this by secretly adding a parameter to hold the address of where the return object should be constructed.
Excellent explanation, thanks. Rust’s move semantics around “all types must survive a memcpy” are (IMO) a great idea 99.9% of the time (no move constructors, no worrying about “pillaging” the source of a move to make its destructor safe to run, you can express more invariants since you don’t need to be able to express such pillaging) but it’s one of the places where something that is “simple” in C++ is truly hard to accomplish in Rust.
Rust has added Pin later on in the language to express data that can’t be moved, but IME I only see it used in desugared async code to guarantee that values stay put between awaits, and it’s not common to see Pin used for general code. I don't think you can just sprinkle some Pin<T> into existing code and solve the object identity problem, although I've never really had to deal with code that's move-sensitive so I don't know.
Then you have languages like Rust, Go, Zig, etc which don't have them at all, constructors are just static functions in the namespace of the type, which return an instance of that type.
For the life of me I've never understood why you'd want the former. I'm sure there's a reason, but I never miss it when using languages in the latter category.
The explanation you typically hear is about OO and inheritance, but I don't buy it: If Animal had a ::new() that initialized private state, Cow could have a ::new() too that could call Animal::new() if it wanted, then do further initialization, etc... I don't think there's anything about inheritance that says constructors are a must. (Edit: In fact, ObjC does exactly this. I should have remembered that given that I did ObjC for a living for a while.)
Replies (13)
Thus you need all mechanisms to implement the same capabilities, thus constructors, by the way they are not alone in this approach.
Replies (2)
Replies (2)
If the only way to initialise a class-type object was to call some custom static method on it then you'd have to write "Foo x = Foo::create();". Suddenly it looks more special than a built-in type.
Replies (2)
I guess the argument might be that for C++, they want the author of the type to determine whether the value should be left uninitialized on declaration/construction, instead of the caller. Which is... not exactly the semantics I would have chosen.
Replies (3)
Continue this thread (2 replies) →
Thus a default constructor replicates a plain int x;, whereas the copy constructor or single value constructor is used for int x = 42;.
By the way, already in the 16 bit days you could configure to have warnings as errors for variables being used without initialisation.
Continue this thread (1 replies) →
Replies (1)
https://www.ralfj.de/blog/2019/07/14/uninit.html
Continue this thread (1 replies) →
Replies (1)
Replies (1)
core::mem::uninitialized is of course unsafe, but what people who designed it hadn't really appreciated was that in most cases it was impossible to use it correctly, it almost might as well have been a call to core::hint::unreachable_unchecked
If your type is a ZST then core::mem::uninitialized was safe to use, because not initializing zero bytes of RAM is the same as initializing all zero of them, this can't possibly matter so we're fine. Otherwise though, we create values which the LLVM backend is sure we cannot know and so it feels entitled to optimise as if any assumptions we make about those values are false, even if the results are contradictory. This causes immediate Undefined Behaviour all over the place.
The MaybeUninit<T> wrapper type is pretty easy to use and won't invoke Undefined Behaviour so long as you do everything in the instructions.
Continue this thread (1 replies) →
Also I was under impression that Rust at least has a similar goal?
Replies (2)
Replies (1)
The latter was what I was interested in, and I apologize for not making that clear. For instance, in Rust terms both those seem replaceable in principle via calls to appropriate trait functions like Default::default() or From::from().
Replies (2)
Which is why the only difference between a struct and a class, is the default access method.
Thus that C file could be made extensible in C++, with zero code changes on the call sites.
Continue this thread (2 replies) →
The question is, at least for me, do you really miss out on anything by not having an ability to do so? I think you miss anything, but you gain a lot.
Continue this thread (1 replies) →
Rust's choice here is slightly different, Rust wants to give all of the types features, whereas C++ wanted to specifically give the user defined classes as much functionality as possible.
So in Rust 5 and "Five" and '5' and [5, 5, 5, 5, 5] all can have the features you get in your own custom type named Five whereas in C++ they do not. In C++ they're not allowed to have methods ("member functions") because they are "just" primitive types. In Rust the operators are actually implemented for all the types they can be used on, not just for your own user defined classes and so on.
In a few cases this is "fake", for your own type to have a + operator you'd have to write an implementation of addition and the Rust stdlib provides an "implementation" for the machine integers which says nothing of importance because of course in reality that code is never executed, the Rust compiler knew how to add two integers together already. However most of them are real albeit often trivial.
Because Rust doesn't privilege a specific user defined type, all the user defined types get the features which make sense, including not only struct but also enum and union. It still surprises me that C++ never gave enum class (its improvement on the C enum user defined type) methods, of course a Rust enum has methods.
However, create-and-return makes in place construction difficult. C++ allows you to construct directly into any pinned memory block with satisfactory size and alignment, whereas create-and-return requires you to construct elsewhere and then copy the bytes. This has downstream implications:
- The address of "this" always changes at least once, which makes self-referential data structures and cyclic data structures more difficult. Now you have a pointer fixup step, or you are passing around some form of handle rather than raw pointers. These solutions can range from trivial to complicated, fast to slow, depending on the specific patterns in your code base. A simpler work around is to always construct with a fresh heap allocation and return a pointer to it, which, again, may or may not be an acceptably performant solution for your particular problem.
- You have to rely on your optimizer to do copy elision, which is not a guarantee. Not an issue for small objects, but it can become an issue for larger ones or for many repeated constructions.
Replies (6)
Given that, it seems like a language could be designed so that a static method that returns an object could be allowed to construct an object in place. Again, I don't know enough about Rust or Zig to know if that's true of them.
Replies (3)
What happens inside
can be as "inefficient" as your example above, but the compiler would validate & figure out a way to make it an in-place-construction, guaranteed RVO.(similar to `constexpr` validation)
EDIT: Looks like this already exists under several names ("build-in-place", "placement by return", "result location semantics") in Ada's `return W : Widget do ... end return;`, Carbon's returned var c: Circle; ... return var;`, and Rust has (still open) RFC 2884 "placement by return", and Zig seems to have this fully built-in via result location semantics?!
Replies (1)
In c++ this is solved[1] via 1) emplace_back 2) perfect forwarding 3) constructors having an homogeneous name and being selected via overload resolution.
In a language with RVO, it is not enough for 'make_foo' in 'push_back(make_foo(args...))' to guarantee zero copy, 'push_back(x)' must also be able to guarantee that its parameter x is somehow constructed in place.
In practice you need some form of lazy evaluation (call by name, or an explicit thunk or passing the function and parameters separately) or some form of macro expansion.
[1] it does comes with its own set of foot-bazookas of course.
Ome can make it guaranteed (assuming Foo is an aggregate) by writing:
This guarantees initialization happens at the end of the function, since you are returning a pure rvalue. Generally a good style rule to adopt and no annotations needed.Replies (2)
(except they’re right and you just gained +1 to wisdom)
Replies (1)
https://en.cppreference.com/cpp/language/aggregate_initializ...
Generally, when you're doing the
pattern, it's because Foo is a struct with only public members and no constructor used for passing data around. e.g. When it's that simple rather than type out: You'd type: Congrats the code is shorter!Continue this thread (1 replies) →
But still, doing `std::make_unique<T>(args...)` or allocates storage and guarantees to run T's constructor there, and you can even do `std::optional<std::mutex> slot; slot.emplace();` which builds the mutex inside the optional even though a std mutex can't be moved or copied.
This is definitely the closest thing to an answer in this thread. This is something that languages without constructors do struggle with, yes, and as other commenters pointed out, Rust sees this as a performance issue and is working on it.
Thanks for the informative reply.
That's difficult to believe for a C-like language..
Replies (1)
But in C++ and Rust, assignment itself is a method which can be overridden. So what does it mean to call a method on an object that doesn't exist yet? Also, destructors have to be run when an object goes out of scope. But what if an error occurs before all the fields have been assigned - now you're destructing objects that don't semantically exist yet, and whose memory contains garbage.
That's why I say it's a trade-off - if they wanted, the designers of C++ and Rust certainly could have just allowed programmers to paint themselves into such corners. But they preferred to disallow these things entirely and instead require objects to be constructed all at once as a semantic unit.
Replies (1)
However this is a very bad and unnecessary hack, which I consider as the worst mistake of C++ (already present in the first "C with Classes", before becoming C++).
The correct solution is to distinguish output parameters from input-output parameters, like e.g. in Ada.
The difference is that an input-output parameter contains memory on which some object has already been constructed before invoking the function, while an output parameter contains uninitialized memory upon function entry.
In a language that has 3 parameter types (input, output and input-output), constructors are just ordinary functions that have an output parameter of the type that is constructed. No special treatment for constructors is needed.
When defining classes, one would have to optionally specify only a default constructor and a destructor, because these must be invoked implicitly by the compiler. Any explicit initialization of an object would use arbitrary functions with suitable parameter types.
The result parameter of a function should be an output parameter. If an already existing object is passed as an output parameter to a function, inclusively for its result parameter, the compiler would invoke implicitly the destructor for that class, before invoking the function.
Both output parameters and input-output parameters may be passed either by value or by reference, based on compiler or on ABI choices that are appropriate for their types.
When output parameters are passed by value, in registers, the compiler will store an output parameter from its register to the desired location, after the function returns, while when input-output parameters are passed by value, in registers, the compiler will load those registers before invoking the function and store them after the function returns.
Replies (1)
Replies (1)
Replies (1)
One is that C++ has constructors, with lots of rules about which one is called when.
But the other is that primitive objects can sometimes be uninitialised, and sometimes that's what you want for performance (if you're about to overwrite them anyway). C++ classes are meant to be able to do anything a primitive type can (as a sibling comment says) so you sometimes want a class that you can either leave uninitialised or value initialise (essentially, set everything to zero) decided at the call site (not in the class declaration).
If C++ guaranteed that all members always had to be initialised, then all the default-like constructors (Foo x; Foo x = {}; Foo x = Foo(); etc) would resolve to the same thing (a call to the constructor you explicitly wrote if you did; otherwise all members default constructed, resolved as zero-initialisation if that's equivalent).
Replies (1)
So as usual with C++, we end up with a half-working system, with subtle footguns, pervading all of the program code, and impossible to ignore.
The C++ design bets heavily on that. Just like you can overload an operator, you can also overload the meaning of `=`, `new`, variable declarations, and etc. That necessarily leads to an awful complex language, but also a very powerful one that can potentially lead to very easy to read code in high abstraction levels.
The problem both C++ and Swift have is that you can't really build high abstraction levels, because the languages are designed in a way that makes some fixed concerns creep over your entire code.
Replies (1)
Replies (1)
Outside of that, Swift has only normal OOP constructors, that are something completely different, and almost not a pain at all. Normal constructors are just a control layer on top of memory initialization that lets you write custom rules for it. It becomes necessary when you have protected memory in your objects, because the external code can't just go and set it, but even languages like Python understand it's convenient to have a defined place to set things up.
Replies (1)
Replies (2)
Replies (2)
Heck, Smalltalk is the original OOP language and has implementation-based inheritance, and construction is done through ordinary methods on class objects.
Replies (1)
Smalltalk is even worse, but it also has the philosophy that anything can be patched at runtime, so it kind of is in line with that.
This is basically about static type safety.
You could in principle enforce proper initialization and encapsulation by static analysis requirements instead of by a dedicated language construct. The latter is traditionally more efficient however, and arguably makes the code more explicit about its intent.
I'm not even sure about the former? The important bit is that base class invariants can't be observed in an invalid/inconsistent state, and regular visibility/privacy/etc. rules seem technically sufficient for that? I'm not sure where exactly the boundaries of "constructor-like concept" are supposed to lie.
Replies (1)
If so, I think the difference is that in C++/Rust RAII is the default and is quite pervasive as a result. To-be-closed variables seem like IDisposable in C# or try-with-resources in Java in that they allow the programmer to use RAII-like semantics but are opt-in.
Replies (1)
Continue this thread (1 replies) →
Replies (1)
Constructors make alot of sense to me. It's a promise to the caller that the instance is fully initialized after it returns.
But there are cases where it simply ain't possible. For exampIe I always struggle with object pools, where you construct a bare instance and reuse it later on. In such cases it is often very cumbersome to to guarantee that each instance is properly initialized and uninitialized in every case. It gets worse when different instances are involved, depending on each other. The more classes there are, the worse it gets.
The whole idea of OOP, aside from inheritance, is that the class implementation controls and ensures the invariants of its instances, protecting their internal state from client code. This limits code that might accidentally leave the object in an invalid state to the class implementation. If the class implementation is correct, then the object can’t possibly get into an invalid state, because only the class implementation can manipulate that state. And, importantly, that encapsulation boundary also exists between superclass and subclass. Conceptually, from the perspective of the superclass, a subclass is client code just like any other client code, from which the internal state of the superclass instance has to be protected.
Hence there needs to be a concept of dedicated initialization functions to guarantee that instances are always properly constructed and client code outside the class can’t end up with a half-constructed object and/or see an object in uninitialized state. And with respect to a superclass, the code of a subclass is “outside the class”.
Replies (1)
Replies (2)
One useful feature of constructors still doesn't exist, which would be the placement new style thing, but that's on its way as well, and is an optimization rather than a requirement for most cases.
Replies (1)
Replies (1)
Continue this thread (2 replies) →
Arthur O'Dwyer's crusade against CTAD (<https://quuxplusone.github.io/blog/tags/#class-template-argu...>) ultimately boils down to this problem, which is not really type deduction itself, but ambiguous overloads, which are hard to avoid when constructors are the only way to create an object, without resorting to clumsy workarounds like tag types (which create problems of their own).
There are other problems too, like the fact that you cannot call std::make_unique (or emplace) for a class with a private constructor even in a scope where you have access to the constructor itself.
Replies (3)
Replies (1)
In JavaScript, how do you use new Array(...) to create an array consisting of a single integer? You can do the same with a single value of any other type.
The reason these languages don't have the make_unique or emplace problems is because they don't have a concept of in-place construction at all, since objects in those languages are heap-allocated and have reference semantics anyway.
Replies (2)
More importantly, you have exactly the same problem if you overload a regular method that way. So it’s a problem with overloading, not with constructors.
> How do you construct a MyVector of two items?
The correct solution, of course, is to provide named static constructor methods instead (e.g. `MyVector.ofRange(start, end)`).I do agree that support for named actual constructor methods would be nice. But they would still be constructors.
If you Vec::with_capacity(5) both you and a reviewer know what's going on here - this is clearly a Vec with capacity 5.
When you call a C++ constructor with 5 as the parameter, both you and the reviewer had better be sure what that 5 means.
When I used to program in C++, my general rule was that applications follow the "rule of zero" (no explicit constructors), and libraries do what's needed to make the rule of zero work for applications.
Replies (1)
Replies (1)
If more logic surrounding their construction is needed, you can use factory functions.
Replies (1)
But in C++ one variable is one object. When you write "mystruct foo;" a new mystruct is created at that point. That is a specific one that has a specific memory address and is not interchangeable with any other. If you wrote "mystruct foo = create_mystruct();" that would be kicking the can down the road because the mystruct that is returned by create_mystruct is not the same one as the variable foo, so you still need a constructor to initialize foo based on the result of create_mystruct before the result mystruct is destroyed. You could define it to be a bitwise copy but that wouldn't work for a lot of types (like string, or shared_ptr).
In a language like C, you define it as a bitwise copy and anything that becomes incorrect after a bitwise copy is left as an exercise to the programmer. In a language like Rust you have a strong ownership model that permits a bitwise move - which is the same as a copy, but the original is no longer considered an object, and won't have its destructor called, and the destination wasn't an object until it was copied into. This requires that the object doesn't hold a pointer to itself. In C++ you have neither and you have be able to call user-defined code here.
Later versions of C++ have something called RVO which actually allows the copy to be omitted but only in the specific case above. Other cases still need copies. The language is tortured to say that create_mystruct's return value isn't actually a separate temporary instance of mystruct but whatever goes in the return expression of create_mystruct is actually used to construct foo in the caller. Compilers implement this by secretly adding a parameter to hold the address of where the return object should be constructed.
Replies (1)
Rust has added Pin later on in the language to express data that can’t be moved, but IME I only see it used in desugared async code to guarantee that values stay put between awaits, and it’s not common to see Pin used for general code. I don't think you can just sprinkle some Pin<T> into existing code and solve the object identity problem, although I've never really had to deal with code that's move-sensitive so I don't know.