Rendered at 08:56:36 GMT+0000 (Coordinated Universal Time) with Cloudflare Workers.
ninkendo 17 hours ago [-]
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.)
Calavar 17 hours ago [-]
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.
quietbritishjim 16 hours ago [-]
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.
aw1621107 16 hours ago [-]
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).
jjmarr 14 hours ago [-]
> 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.
reactordev 10 hours ago [-]
What is this abomination? This syntactic aversion to my eyes…
(except they’re right and you just gained +1 to wisdom)
jjmarr 5 hours ago [-]
The serious answer is it's the ultra-rare aggregate initialization constructor.
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?!
gpderetta 12 hours ago [-]
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.
ninkendo 14 hours ago [-]
> 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.
Thanks for the informative reply.
renox 12 hours ago [-]
So Zig makes 'build-in-place' hard?
That's difficult to believe for a C-like language..
wavemode 11 hours ago [-]
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.
kibwen 10 hours ago [-]
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.
stackghost 16 hours ago [-]
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.
layer8 15 hours ago [-]
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”.
pwdisswordfishq 14 hours ago [-]
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.
steveklabnik 14 hours ago [-]
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.
layer8 14 hours ago [-]
Rust doesn’t have implementation inheritance. If it did, it would need a constructor-like concept as well.
gpderetta 12 hours ago [-]
With guaranteed RVO you could do something like this (pseudo-C):
How is it ensured that make_foo will actually call make_foo_base?
gpderetta 8 hours ago [-]
You are right, sorry, lost track or the thread.
quietbritishjim 17 hours ago [-]
There's really two things in play here.
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).
Joker_vD 10 hours ago [-]
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.
pjmlp 17 hours ago [-]
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.
aw1621107 17 hours ago [-]
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?
pjmlp 17 hours ago [-]
Initialisation syntax, and temporary values for implicit conversions, is what is lost.
aw1621107 16 hours ago [-]
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().
pjmlp 15 hours ago [-]
Nope, because you also want C types, that now are C++ types by virtue of using a C++ compiler, to also share similar behaviours.
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.
pwdisswordfishq 15 hours ago [-]
What does this have to do with anything?
ninkendo 15 hours ago [-]
They could have just as easily said "C semantics are used when we know we're parsing C code" and declared that C++ code doesn't have implicit constructors. No, the decision to have constructors was made because it's what they wanted to do when the language was designed. You can't lean on "but C" as an excuse when those problems are so easily solved other ways.
0x457 13 hours ago [-]
Well, in Rust, you can't make your own Box without using #[lang = "owned_box"] and #[fundamental], plus it has special orphan rule handling.
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.
aw1621107 12 hours ago [-]
> Well, in Rust, you can't make your own Box without using #[lang = "owned_box"] and #[fundamental], plus it has special orphan rule handling.
Sure, but are those "just" characteristics of Rust's current implementation or are those inherent to a constructor-less model in general? The latter is the more interesting question to me in this particular context, and I think it's similar to the question you express.
0x457 11 hours ago [-]
Fair.
I think guaranteed in-place initialization is probably the strongest example of something that cannot be expressed through From or Default alone. There are proposals to solve this via traits. I haven't dug deep enough into them, but I'd assume those would be "special" traits that rely on compiler-provided semantics not otherwise expressible in ordinary library code.
Right now, both Box::new() and the vec![] macro resort to compiler intrinsics (write_via_move and write_box_via_move), particularly to avoid unnecessary intermediate storage and excessive stack usage.
aw1621107 4 hours ago [-]
At least from what I can remember the work is in an early enough stage that multiple proposals being considered. IIRC dedicated syntax is in the cards as well.
17 hours ago [-]
ninkendo 17 hours ago [-]
I don't see the link between constructors and whether or not built-in types have special treatment. Care to enlighten the class?
quietbritishjim 17 hours ago [-]
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.
ninkendo 16 hours ago [-]
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.
steveklabnik 14 hours ago [-]
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>).
pjmlp 15 hours ago [-]
It is up to the constructor to only initialize storage, or do whatever it feels like to have values assigned to it.
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.
ninkendo 15 hours ago [-]
> It is up to the constructor to only initialize storage, or do whatever it feels like to have values assigned to it.
Right, see the "I guess the argument might be" part above... I find this to be a very questionable design choice, leaving you to have to go and read a header somewhere to determine whether `Foo f;` is safe or not. But it's not really a choice, is it? C++ had to do it this way to be compatible with how C programs were written back in the 1970s.
> By the way, already in the 16 bit days you could configure to have warnings as errors for variables being used without initialisation.
Ah yes, the "but C can be configured to be not-insane" argument, one of my favorite pjmlp-isms, right up there with "but $LANG's compiler is written in C++" and "but you already get memory safety with a GC". Keep on doing you!
quietbritishjim 16 hours ago [-]
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?
tialaramex 15 hours ago [-]
Rust has a Default trait, if your type Goose has a Default then
let foo: Goose = Default::default();
Those "primitive" types have a Default, the integers default to zero, as do the floating point types, bool defaults to false, I believe an empty string is the default string (in both the sense that's the default for String, and the default for str, the string slice reference roughly analogous to C++ string_view)
Some things don't have a sane default, just as those things wouldn't provide a zero argument constructor in C++. There isn't a default file descriptor, a default network socket, and so on and so those types do not implement Default
quietbritishjim 14 hours ago [-]
That makes sense, thanks!
ninkendo 16 hours ago [-]
Yep, that's std::mem::zeroed(), which just writes zeroes into the allocated memory regardless of its type... also only available in unsafe code.
It's unsafe because if Foo contained a String, it would be string with a null pointer inside it and you'd crash trying to read it. If you want "Default" values instead of zeroed (ie. you don't want to run unsafe code), that's what the Default trait is for, and this becomes:
If my understanding is correct, C++ built-in types can be declared without initializing them:
int x; // Unitialized, garbage value
int x{}; // Value-initialized (falls back to zero-initialization)
We want classes to have the same behaviour:
Struct s; // Default-initializes (presumably we want members uninitialized)
Struct s{}; // Value-initializes (presumably we want members initialized)
ninkendo 16 hours ago [-]
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.
tialaramex 15 hours ago [-]
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.
ninkendo 15 hours ago [-]
I literally had `MaybeUninit::uninit().assume_init()` first in the comment but rewrote it with `std::mem::uninitialized()` because I thought it would be more readable to a C++ crowd, but perhaps your right, I should have left it as-is.
tialaramex 14 hours ago [-]
MaybeUninit::uninit().assume_init() is, exactly like the deprecated† core::mem::uninitialized() immediately UB unless your type is zero size and thus there's no difference between initialized and uninitialized.
You can unsafely ask for an uninitialized value of any type, but you should not ever assert that you've initialized it unless you actually have. Essentially, you can write this in Rust, but you need to be specific about what you're doing and when you are or are not initializing the variable or else things will go badly for you.
It wouldn't be worse in C++, historically, but C++ people are more used to their world being set on fire by an angry compiler because they did something wrong. In Rust you'd be quite surprised by the compiler's wrath.
† Edited to add: Technically today you do not get this if you call core::mem::uninitialized, because it was so dangerous, instead if you call the deprecated function on a non-ZST - ironically you get a a value scribbled with 0x01 bytes. Doing this ensures in most cases LLVM won't set fire to your program immediately but at a price of doing all that extra work of writing 0x01 bytes. But we did tell you (for several years now) how to do better.
ninkendo 13 hours ago [-]
I completely agree, but the point was to show Rust code that does the same thing as the (equally unsafe) C++ code, and particularly that it doesn't treat built-ins any different than other types. But nobody should be writing code like this in either language.
To me the whole point of an "uninitialized variable" is to declare it in one place and then assign it in exactly one code path, which is exactly what rust supports without any unsafe code:
let i: i32;
if is_tuesday {
i = 0;
else {
i = 1;
}
foo(i);
is already perfectly valid, safe rust code, because the compiler knows that all code paths result in assignment before use. And the answer to "what happens on that first line?" is "nothing", because it's just a declaration. In the equivalent C++ you'd be running an arbitrary constructor on the first line, and hoping the compiler optimizes it away. Or if the default constructor doesn't exist or is deleted, you simply can't code that way.
tialaramex 9 hours ago [-]
Your code snippet is fine, but MaybeUninit comes into its own when it's not obvious to the compiler that what you wrote is OK - MaybeUninit::assume_init is how you tell the compiler "I promise this is correctly initialized" and so long as you're correct, everything is fine. By Rice's Theorem no compiler could ever be sure all the time, and in fact Rust choose to be extremely pessimistic, obvious things like yours work, non-obvious things do not and if you write a ticket about a case you feel ought to be obvious but was not (please don't) the Rust folks will say that is as intended, here are some alternatives to achieve what you meant, up to and including MaybeUninit
lefty2 16 hours ago [-]
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.
zubspace 12 hours ago [-]
This is something I struggle with alot.
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.
raegis 13 hours ago [-]
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.
pwdisswordfishq 14 hours ago [-]
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.
tialaramex 14 hours ago [-]
Yes, the ergonomics are just better
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.
edflsafoiewq 11 hours ago [-]
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.
layer8 14 hours ago [-]
These aren’t problems with the constructors per se, though. E.g. Java doesn’t have any of these problems.
pwdisswordfishq 14 hours ago [-]
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.
layer8 14 hours ago [-]
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.
vips7L 11 hours ago [-]
It’s ambiguous to the reader, but the JLS strictly defines which constructor would be called here. It’s the int a, int b constructor.
marcosdumay 17 hours ago [-]
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.
ninkendo 17 hours ago [-]
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.
marcosdumay 15 hours ago [-]
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.
xscott 14 hours ago [-]
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.
pwdisswordfishq 13 hours ago [-]
Rule of Zero is not actually about constructors other than the move and copy constructors.
wavemode 10 hours ago [-]
Rule-of-zero classes don't need regular constructors either, since you can just aggregate-initialize them.
If more logic surrounding their construction is needed, you can use factory functions.
xscott 8 hours ago [-]
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.
9 hours ago [-]
15 hours ago [-]
binary132 16 hours ago [-]
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.
aw1621107 16 hours ago [-]
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.
layer8 14 hours ago [-]
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.
aw1621107 13 hours ago [-]
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.
ninkendo 14 hours ago [-]
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.
layer8 13 hours ago [-]
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.
binary132 5 hours ago [-]
I mean, by that logic, so does Lua, but nobody goes around saying Lua has RAII.
badpun 15 hours ago [-]
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.
This is just a single section of the first chapter of a beginner tutorial. And it's already more things to remember than, say, the whole Lua.
tavavex 15 hours ago [-]
The real kicker is the countless ways in which code that looks normal at a glance is subtly wrong in ways the language will not warn you about. There's a trillion ways to do anything in C++, spread over multiple decades of language design, each way involving a hundred lower-level considerations you've never heard of but must know to understand which one to pick, and what feels like half of the approaches causes some random subtle memory leak or undefined behavior.
pjmlp 17 hours ago [-]
I know C++ since 1993, naturally don't know everything about the language.
I also don't know everything about Java, .NET, Python, JavaScript, SQL, HTML, CSS, and yet work gets done.
To use other languages as example, I bet most folks would fail a pub quiz based on the latest version of those languages, now with about 20 to 40 years history as well.
LeFantome 16 hours ago [-]
Very true of course, but there is a difference.
For what HTML and CSS get used for, the consequences of not knowing everything are fairly low. If it does what you want, it does what you want. Things could maybe be better but they are probably also fine.
SQL is mostly the same though perhaps the performance implications of not knowing it well are higher.
For .NET, Java, and Python things are not much different. If they do what you want, there is probably not much risk that they are doing things you don’t.
JavaScript and, even more dramatically, C++ are quite different. They may be doing what you do not want, or it may be easy for others to make your code do things you do not want. Not understanding the nuance or idiosyncrasies in those languages can do a lot of damage.
Complexity has another angle. If I am working with other people’s Python code, the chance that I will not understand it is low. If I do come across a new feature in .NET or Java, I will spot it right away and will probably be able to research it, learn it, and move on very quickly. Same with HTML and CSS. .NET and CSS are great examples of languages with quite a bit of complexity but where the burden of that complexity is reasonable when maintaining code.
But again, JavaScript and C++ are not that way. C++ code using features I am not familiar with can be a massive burden to unpack and understand. I may not even realize at first that something I do not understand is in play. And, as above, I may not actually understand it as well as I think I do. And that lack of understanding may have surprising consequences.
To your point, A LOT of work still gets done. But perhaps less re-work (so more work) and less risk is possible.
pjmlp 16 hours ago [-]
There is this thing called static analysers, that while they are not perfect, are quite good guard rails into what to use in terms of best practices, regardless of the programming language.
Code quality would be much better in general if everyone actually used "clippy".
Which is anyway a moot point in the age of AI generated code.
kstrauser 17 hours ago [-]
That’s true on the face of it, but not knowing all of C++ vs Python is like not knowing all of Russian vs Toki Pona. Yes, it’s possible to study both languages and still miss portions. Getting to 80% fluency on one is vastly harder and more complicated than with the other.
pjmlp 17 hours ago [-]
I bet most folks using Python have no clue about how close it is to C++ and Common Lisp in terms of capabilities, across its language, standard library, runtime capabilites and C FFI.
They assume the myth that Python is a programming language for beginners and never do a deep dive into what is available.
Worse, due to lack of compatibility across releases, it is rather easy to have code break and be blissful unaware of what a specific point release has changed.
When I learnt Python, the current version was 1.6 and Zope was everywhere, I guess I know a thing or two about its evolution and related complexity.
tolugenius 17 hours ago [-]
C++ is a language I heard is very "beginner unfriendly, and expert friendly" and it's true, I'm trying to relearn and really not clicking with me, anyone have tips on relearning or better sites than even learncpp?
gaflo 11 hours ago [-]
I wouldn't say it's expert friendly either. It is very powerful, but it's definitely not as ergonomic to use as more modern languages. Before agents/LLMs you would probably have cppreference.com open every time you are implementing something to check whether the STL is designed as you think. Compilation errors are as explicit as it gets (and thus a bit verbose), but they would help an expert to very quickly understand what was going wrong in a program.
I think part of the problem is that there are usually 3 different ways to achieve the same semantics, but there would be some subtle technical differences. From my perspective a lot of the problems with C++ come from the incoherent vision for what the language was supposed to be and especially the insistence on backwards compatibility caused significant bloat (design/technical debt) over time.
William_BB 17 hours ago [-]
Classic C++ books and cppcon are probably the best ways to learn the language if you don't have exposure to a modern C++ codebase (at least C++17).
pjmlp 17 hours ago [-]
Tour of C++, last edition, would be a good one.
coldpie 17 hours ago [-]
Learn (like, really learn) C first. C is a reasonably easy language to learn, with only a few weird corners mostly due to its relevance to very old computing concepts. Build a few toy programs, maybe a video game or two, play around with memory allocations and struct aliasing and file I/O and function pointers.
C++ is (wave hands vigorously) roughly built on top of C's core concepts, so if you know C really well you can (continue waving hands) actually map most of C++'s basic concepts on top of how C works. For example in object methods, the 'this' pointer is actually just silently passed as the first parameter to a function. Class vtables are (at a very abstracted level) just arrays of function pointers. Letting you map those concepts down to a simpler representation like C means C++'s magic starts to lose its magic. Understanding how the class hierarchy is mapped to C can tell you why the 'virtual' keyword exists, and why you need proper copy constructors for those objects but not ones without vtables; and it gives clues for what pure virtual functions are, and why you can't allocate an object with one.
So yeah. Start with C, then figure out the bizarre, incredibly complex maze of abstractions that C++ stacked on top of it.
pjmlp 17 hours ago [-]
This will only bring bad practices in modern C++, the root of all C/C++ discussions in security reports.
coldpie 16 hours ago [-]
Curious if you can elaborate. I found learning C to be a really good stepping stone to understanding many of C++'s design choices (eg stuff like why the 'virtual' keyword exists & works as it does; or why a class's private members must be declared in the public header). It also gets you more familiar with non-interpreted language concepts like the compiler and the linker before C++ turns those into multi-headed beasts.
pjmlp 16 hours ago [-]
C raw arrays and strings should only be used for "unsafe" C++ code, in the implementation of safer types, with bounded checked interfaces, or in interop code with C libraries, properly wrapped in safe accessors for example.
Use of references for any non nullable pointer.
RAII for heap allocated types, eventually new/delete, leave malloc()/free() family with sizeof type math for interop with existing C code.
Prefer standard library algorithms with proper bounds checking, instead of memsomething and strsomething function family.
Preprocessor magic, when templates and constexpr are type safe, and can even be single stepped on a modern IDE.
Just some examples out of my mind.
PhilipRoman 15 hours ago [-]
I wholeheartedly disagree with the idea that all C++'s problems come from backwards compatibility with C. Even "pure" C++ alone without C constructs brings enough footguns.
struct Config {
std::vector<std::string> names;
const std::vector<std::string>& getNames() const { return names; }
};
Config loadConfig();
// which of these are safe?
for (const auto& n : loadConfig().names) { use(n); } // A
for (const auto& n : loadConfig().getNames()) { use(n); } // B
const auto& v1 = loadConfig().names; // C
for (const auto& n : v1) { use(n); }
const auto& v2 = loadConfig().getNames(); // D
for (const auto& n : v2) { use(n); }
Trick question btw
plorkyeran 13 hours ago [-]
C in C++20, A, B and C in C++23. This does sort of fall under a backwards compatibility issue, albeit not with C, as making D valid was considered too much of a breaking change.
PhilipRoman 11 hours ago [-]
I'm no C++ expert, but in P2012R0 it even gives this specific example, indicating that A is OK in c++20:
[..]
One recent real-world example by one of
the authors is the following:
Improving the following code:
struct Person {
std::vector<int> values;
…
};
for (auto elem : createPerson().values) { // OK (lifetime extended) <-----------
by introducing a getter to have better encapsulation, suddenly caused the undefined behavior:
class Person {
private:
std::vector<int> values;
…
public:
const auto& getValues() const {
return values;
}
};
for (auto elem : createPerson().getValues()) { // UB (fatal runtime error)
Or else you could have "loadConfig()" be a method that returns a reference, which is in turn the member of a class, so that there isn't any dangling reference issue.
JdeBP 7 hours ago [-]
"You could write it completely differently." is just a more general case of "You could write it in Rust instead.". And it's missing the point.
The point being made is that the stumbling blocks exist to be tripped over by the unsuspecting, and are not because of C.
0x457 12 hours ago [-]
I'd distinguish between understanding why C++ was designed the way it was and learning how to write idiomatic C++. C is certainly useful for the former, but many practices considered perfectly normal in C are considered (very) bad practice in C++.
This is also why I dislike the term "C/C++" when referring to them as if they were a single language. They are two distinct languages with substantially different idioms.
What I hate about C++ is that it offers a myriad of ways to accomplish the same thing, ranging from outright terrible to genuinely good. Learning C first can reinforce habits that you'll later have to unlearn.
trealira 16 hours ago [-]
But that only happens if you fail to learn everything in modern C++. If you want to know everything about C++ inside and out, it seems best to start with learning C inside and out, and then to learn which practices have been superseded by better alternatives in C++ and how C++ has changed them, e.g., how initialization has been complicated.
pjmlp 16 hours ago [-]
The problem is that many end up writing C style code in C++ and never bother with best practices, unless they have a proper mentor refusing PR for example.
thinkoid 10 hours ago [-]
It's not a curse, you know. You do not HAVE to bring those practices into C++, only use the learned material to peek under the hood of C++ (not even so, but as the guy above suggested, glimpse into). If only I had a dime for every curmudgeon who took your dogmatic position and tried to scare someone away from C.
There is no better way to understand what's going on in std::vector or std::string than writing a growable array in C and having to keep three facts straight: how much storage you own, how many elements you’re using, and who releases it. Knowing how much work the abstraction does is a damn good reason to use it.
pjmlp 2 hours ago [-]
That knowledge can be acquired by teaching C++ only, and in fact it was the approach taken in my university during the 1990's already, quite forward looking.
First Pascal for those that never coded in their life, and then C++.
The other languages that had explicit learning material were Smalltalk, Caml Light Objective Caml, Prolog, Lisp, Algol, Miranda, Java, PL/SQL, 80x86 and MIPS Assembly.
It was expected that the few classes where C was still used, basically UNIX kernel programming, alongside algorithms and datastructures, the knowledge to code in C would be taken from those C++ classes done during the 2nd year.
So I hold this view for almost 30 something years now.
sobellian 17 hours ago [-]
It's not expert friendly either. The Stockholm syndrome just kicks in.
simonask 15 hours ago [-]
Exactly. C++ programmer confidence is a bell curve, where the X axis is skill level.
The more you know about programming in C++, the less confident you become that your code is actually correct, because you've seen before how the most seemingly innocuous decisions turned out to be massive UB footguns. Even worse if you know anything about how computers actually work - that's not relevant, C++ like C targets an abstract virtual machine with semantics unlike any computer ever built.
The simplest example is signed integer overflow: the bright young student knows all about Two's Complement and mistakenly believes all is well, and the wizened but weary mentor must waste everyone's time to avoid summoning nasal demons.
What an unbelievable waste.
sedictious 12 hours ago [-]
I'd say C++ is so vast that you can keep on encountering bell curves like that. I start working on a project, building confidence in the subset of C++ I'm working with and when I start feeling good about myself, I'm hit with a completely foreign concept
cppquiz is a nice test beyond "trivia". There are a few hard questions addressing topics I've never encountered. For example:
```
#include <iostream>
volatile int a;
int main() {
std::cout << (a + a);
}
```
I would assume that here a is initialised to 0 since it has static lifetime so I'd expect this to just print 0. But the C++ standard specifies that:
> Reading an object designated by a volatile glvalue ([basic.lval]), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression (or a subexpression) in general includes both value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and initiation of side effects. When a call to a library I/O function returns or an access through a volatile glvalue is evaluated the side effect is considered complete, even though some external actions implied by the call (such as the I/O itself) or by the volatile access may not have completed yet.
and if you have side effects unsequenced relative to other side effects (as is the case with operations of the same operand), this is considered UB
0x457 12 hours ago [-]
In practice, it will be 0, assuming no external modification of a. Strictly under standard, its UB.
sedictious 12 hours ago [-]
yes which is exactly why you don't keep those things in mind most of the times. They are mostly academic exercises yet they pop up in your actual code from time to time and you find yourself furiously scratching your head. But my point is that C++ is huge and there is no way any single human can keep the whole standard in their head.
bestouff 17 hours ago [-]
The more you know about C++, the less you're confident about how your code will be compiled.
simonask 15 hours ago [-]
No I'm sure it will compile. But will it silently corrupt the customer's data 5 years down the line due to a compiler upgrade that suddenly exposed UB in a rarely taken code path? Much less sure.
qurren 14 hours ago [-]
C++ wasn't scary until they kept adding feature-of-the-month to the language. I can't understand recent C++ code anymore. Just leave constructors alone. We don't need constexpr. We don't need spaceship operators and all of that nonsense.
benibela 9 hours ago [-]
It became scary when the compilers started optimizing UB away.
Before that you could just read the assembly to know what the code does. Afterwards any compiler update might have change the meaning
aleksiy123 17 hours ago [-]
My favourite programming gif is relevant here I think
I went through this thread looking for this so because it would be absolutely criminal if it weren't included here by someone.
chuckadams 17 hours ago [-]
Reading Effective C++ those many years ago was eye-opening in a couple ways: initially for the intended reason in the title of the book, but later it felt like having a map to a minefield: good info to have, but it felt more prudent to stay out of the minefield in the first place.
Did you already know that? Do all your junior C++ programmers know that? Do you have lints turned on in every C++ project and dep for that?
Cause I had to really look at it to figure it out. And I had to think, "Would Rust allow this code?"
William_BB 17 hours ago [-]
I'm not sure what's so "spooky" about this example. It's really obvious if you know what `std::string_view` is. `Sanitize()` signature is fishy to begin with -- it takes a single string by const ref, but returns a string view. And I don't even consider myself very experienced in C++.
Sure, it'd be nice if the compiler didn't allow you to write this code. But there are worse examples than this out there.
grg0 14 hours ago [-]
I don't think that is a fair assessment. Imagine Sanitize() and its caller are defined in different files, which is a more realistic scenario. On the one hand, you look at Sanitize's signature and it is "fine" (I agree a string_view argument would be better); it is implicitly stating that the caller is responsible for the lifetime of the argument. Separately, you look at the call and it has a good chance of passing inadvertently. Marking std::string's constructor explicit would have been a slight improvement but it still doesn't solve the problem. Overall, the fact that this code is possible and yields different results under different optimization levels is just cooked. As a programmer, I want to focus on solving problems, not on keeping my guard up at 110% and working around bad language design choices.
To reply to GP: many projects specifically avoid the STL.
simonask 14 hours ago [-]
You have to know a lot about C++ to tell at a glance what's wrong with this code. I fall in that category, and I can tell you I think that the signature of Sanitize() looks extremely reasonable!
What's completely unreasonable here is how easy it is for code that looks reasonable in C++ to be deeply dangerous. This is a perfectly normal piece of code, and it looks like the author is even conscientious about nice things like avoiding too many string copies. We shouldn't be out here defending the absolutely unhinged semantics that led to this.
C++ is so extremely hostile that people who try to write good code end up with a very defensive style of programming if they know what they're doing. In my experience, this tends to either almost fully eradicate any performance benefits they were chasing by choosing C++ in the first place, or blow up the time it takes to deliver the product.
William_BB 13 hours ago [-]
I agree with your general sentiment, but imo this particular example is oversold. Maybe I'm wrong.
The difference between const ref string and string view is one of the first things you learn when you learn about `string view`.
To me, the signature of `Sanitize` is fishy because it's implied that the returned string view is of the const ref string argument. But I agree there are more than one ways to break it.
lollollol3 12 hours ago [-]
[flagged]
lollollol3 12 hours ago [-]
What is funny is that Rust has similar or worse issues regarding temporary lifetimes. Only some UB is caught (and in practice only sometimes), issues like deadlocks aren't.
Challenge to you, simonask: Explain why the curly braces here determines whether there is a deadlock or not. Bonus points if you do so without asking for help or looking anything up.
I'm responding so future readers see the answer, because oooh boy am I not engaging with this account.
The curly braces shortens the lifespan of the `MutexGuard` so it gets unlocked before the body of the if-statement. Normally, the temporary used in the if-let pattern lives until the end of the if-statement.
This wouldn't compile if the value guarded by the Mutex wasn't trivially copyable, but it is.
(Note how none of this is UB, just a particularly contrived way to introduce a deadlock.)
But yes, I know that any function with the signature `std::string_view(const std::string&)` or especially `std::string_view(std::string)` is a land mine.
I asked a local LLM to do a code review on it. (gemma4:12b) It flagged the bug, with all caps "THIS WILL CAUSE UNDEFINED BEHAVIOR", and suggested a fix.
cv5005 15 hours ago [-]
For some reason both c++ and rust decided to go with "lets make temporaries have insanely short lifetimes! Kill them immediatly at the first semicolon we can!" and I don't know why. (rust at least makes it a compiler error to misuse them, but still annoying.)
C has a much better design with its compound literals having block scope lifetimes.
coldpie 17 hours ago [-]
I have a theory that the reason people like C++ is because it's challenging to use. It's like a puzzle or a riddle or a Dark Souls game. It feels good to get something done in C++ because there's so, so many ways for it to go wrong that when you do it right(-ish...), it feels like you're a master of a complex skill. This makes it a terrible language for actually getting things done, of course, but people like that feeling of overcoming the challenge, so they keep using it.
cogman10 17 hours ago [-]
Here's the thing. I'd say that C++ is a great language for getting things done.
It gives you one of those fat swiss army knives I had as a kid with a spoon, fork, knife, toothpick, saw, nail trimmer, etc. The problem is it's easy to get dirty and the spoon would get locked in place after one use. But it was there, and it worked (once).
C++ is extremely malleable. I think the reason people like it is very similar to the reason people like lisp. That ability to do horrors like make a lisp interpreter with macros or templates is the charm of C++.
And if you are the only one writing it, it can be a joy because there are few limits to what you can or can't do.
It's only when you have to share a codebase with others that things can get out of hand fast without some committee established usage code and pledge.
tcfhgj 17 hours ago [-]
> Here's the thing. I'd say that C++ is a great language for getting things done.
my productivity sky rocketed when I switched to Rust.
cogman10 17 hours ago [-]
Probably, particularly in terms of writing correct code.
But C++ allows me to really easily write multithreaded code which I can convince myself is safe :) (and most of the time, is correct, just not on the edge cases). Rust makes that painful.
tcfhgj 16 hours ago [-]
> Probably, particularly in terms of writing correct code.
package management, build system, compiler errors, language simplicity (yes, it adds life times, but removes so many other things), Rust macros, language ergonomics (e.g. match, macros, enums, async, if let, etc.), not having to think about certain things going wrong (including not debugging why things went wrong)
> Rust makes [multithreaded code] painful.
Andreas Kling is switching away from C++ to Rust in Ladybird, because of exactly the reversed experience.
I have been using asynchronous multithreading via tokio - something I never dared to in C++.
Alone from the compiler errors I have got doing that, I would assume that I would have been dealing with an unbearable amount of debugging of subtle memory issues.
cogman10 14 hours ago [-]
> Alone from the compiler errors I have got doing that, I would assume that I would have been dealing with an unbearable amount of debugging of subtle memory issues.
Well, that's the thing about rust and async. It's far more restrictive (necessarily) than the bounds of safety. The hard problem rust runs into is that async functions can be executed outside of lexical and the lifetime tracking of the rust language. To be absolutely safe, rust ends up needing to assume that async can be executed with no respect to the surrounding lifetimes.
Rust would really benefit from something like structured concurrency in terms of the lifetimes of async functions.
tcfhgj 12 hours ago [-]
> Well, that's the thing about rust and async. It's far more restrictive (necessarily) than the bounds of safety.
I obviously was not talking about things illegal in safe Rust, which are actually safe, e.g. you cannot send types which are not allowed to be moved across threads across threads in C++ either.
> To be absolutely safe, rust ends up needing to assume that async can be executed with no respect to the surrounding lifetimes.
Yes, C++ is an omnibus language where all things are possible.
simonask 14 hours ago [-]
All things... except non-nullable pointers, movable values, type punning, ergonomic sum types, and the list is frankly much longer.
The only way you could think that C++ lets you do everything is if you've never tried anything else.
materielle 17 hours ago [-]
It definitely has to be more complicated than that. I know the stereotype is that the C++ language lawyers are up in their ivory towers and don’t “get stuff done” like us pragmatic JavaScript or Python developers.
But the reality is a ton of domains like graphics, video games, and cloud infrastructure is built on C++.
I think the Spanner and Chrome devs “got stuff done” for instance.
I could go on a tangent about the whole “maker vs coder” debate that has sprung up around AI. It feels similar to the C++ idea you’re talking about. The idea is that people who actually understand code and computer science concepts deeply are too busy yak-shaving to be productive like us “makers”.
That ivory tower type definitely exists.
But this false dichotomy seems to be defense mechanism more than anything.
There are smart people that are basically better at everything. They understand C++ deeply, but can code in Python too, build massive pieces of infrastructure like Spanner, and now they are better at driving AI, too.
Not that I’m defending any of the horrible language design decisions of C++. But, you see what I’m saying. People who have skills beyond is in one area aren’t necessarily deficient in another area. Maybe they are just smarter and more skilled than us in a ton of ways.
coldpie 17 hours ago [-]
> But the reality is a ton of domains like graphics, video games, and cloud infrastructure is built on C++.
Yeah, legacy reasons. C++ was a decent-ish improvement over C in the early 90s when many of those APIs were being built out. It's the core language for the Windows API. We didn't get a decent, well supported replacement for C++ until like ten years ago. There's a lotttttttt of legacy C++ code that will stay in use for decades more.
I never said people can't be productive in C++, I'm saying the reason they like it is because it's so hard to use. Just like people can get really good at Dark Souls, people can get really good at C++, too, and they have fun doing it. But I still think that's a con of the language, you can get the same or even better code quality with many modern languages with a much lower bar to mastery.
pjmlp 17 hours ago [-]
Nope, I like C++ because it was already Typescript for C in 1993, coming from Turbo Pascal.
Followed by the great developer experience of using Turbo Pascal alongside Turbo C++, later Delphi and C++ Builder on RAD Studio.
An experience that many languages still fail to reproduce nowadays, with exception of Java and .NET tooling.
You don't need to master every single feature.
trealira 15 hours ago [-]
IDK, I just like C++. I don't think that's the reason. It doesn't feel that good to get something done in C++, and it doesn't feel like a puzzle; it just feels mostly straightforward. The language which is actually like a puzzle and which feels good to write is Haskell, in my opinion, but it's not always as easy to get stuff done in Haskell. I suppose this is why many Haskell coders moved to Rust.
nwallin 9 hours ago [-]
> This makes it a terrible language for actually getting things done,
The thing that I like about C++ the most is that it's best language for actually getting things done.
The 'problem' with C++ is that people who want to get things done go to the committee and say, "hey, I need to actually get things done, if you add this language facility, I can actually get things done better," and they'll often just say "ok" and add it to the language. And if you're the sort of person who believes you must use every single facility provided by the language, then you walk away from C++ thinking it's too complicated. But if you're the sort of programmer who's only interested in getting things done, you can simply ignore all that noise and just actually get things done with the facilities that you know and like.
You don't have to use deeply nested templates, complex dynamic inheritance trees, move semantics, Turing-complete template metaprocessing, you don't even have to manually manage your memory if you don't want to. (personally I avoid all of those things except move semantics) But it's there if you need it.
lkjdsklf 17 hours ago [-]
It’s a weird language
On your initial look, it looks like a total nightmare.
The more you learn and use it, you learn that it is even worse than you ever imagined
So you try something else and find yourself in a constant loop of “if this were c++ i could just go xyz, by nooo”
So then you love it
bernds74 17 hours ago [-]
This roughly sums up my feelings. C++ is horrendous, but it's also the best tool I have.
gchamonlive 17 hours ago [-]
Stockholm syndrome we're all vulnerable to. I love bash for instance.
raincole 17 hours ago [-]
Yes, people even have a term for this. It's named after a Swedish city.
CamperBob2 17 hours ago [-]
Soooo glad I don't have to deal with C++ anymore. Sure, AI might end humanity, but in the meantime, it will never have to pay for its own drinks as long as I'm in the bar.
on_the_train 17 hours ago [-]
In a cruel twist of destiny, it doesn't actually get much more complex than initialisation. But it's something that rarely goes wrong. Static analysis has that nailed down.
01HNNWZ0MV43FF 17 hours ago [-]
I hope everyone is doing static analysis!
17 hours ago [-]
fnord77 17 hours ago [-]
lol
int x = 5;
int x {5};
int x = {5}
int x (5);
spacechild1 16 hours ago [-]
The example is pretty contrived because in practice you'd want to zero-initialize the members in the default constructor anyway.
There are only few use cases where you want a default constructor that does not initialize its members. One example are wrappers around primitive types where you want to closely preserve the original semantics. Whether that's a good idea in the first place really depends on the use case.
For example, std::atomic used to default-initialize the underlying value, which led to many bugs in user code. Since C++20 std::atomic uses value-initialization. See https://cplusplus.github.io/LWG/issue2334. On the one hand, std::atomic is now safer to use, on the other hand, it is not an implicit-lifetime-type anymore, which means you can't put it in shared memory without UB...
Another example is glm::vec, which has actually hit me a few times in my own code. At least they recognized the issue and allowed to override the default behavior with the GLM_FORCE_CTOR_INIT define.
dako2117 14 hours ago [-]
I believe there are also cases where you have a member variable which has a complicated initialization that you may want to handle in some sort of manner that is not appropriate for the default ctor. So you may not want to initialize everything right away in this scenario.
spacechild1 13 hours ago [-]
Can you give a concrete example? Why wouldn't you initialize the member to something, e.g. a sentinel value?
Note that if the member is non-trivial, its default constructor is called either way.
jacobcmarshall 14 hours ago [-]
This is one of the core problems with C++. If you ever encounter a language oddity, it's because you're holding the language wrong, and if you just do it The Right Way, you won't have this problem.
C++ rarely pushes the user towards doing the right thing.
morning-coffee 12 hours ago [-]
This is one of the many reasons I left C++ (after investing over 20 years professionally in it) for Rust. Sometimes it is just better to get on with life than deal with pedantic minutiae all the time.
krylon 3 hours ago [-]
Sometimes I think that maybe I should get reacquainted with C++. Then I see a headline like this, and am reminded I really shouldn't. No hate, but that just is not for me. I deeply respect people who can wrap their brains around all these arcane rules, but my brain just refuses to do that.
Panzerschrek 4 hours ago [-]
What prevents C++ compilers to process a constructor with inline body consisting only of {} as =default? As a compiler developer I can say, that such a change is almost trivial to implement.
That’s what Stroustrup does and it works. I just too versatile. Luckily there is recently a push_back against adding new stuff for the sake of it.
My own rules, mine:
* Templates are nice.
* Template Metaprogramming is not.
* Objects and Classes are nice
* Inheritance is not.
I like composition and interfaces. I avoid inheritance, aside from some natural cases were it fits (UI Widgets).
I’ve seen in recent years projects switching from C to a mere plain C++. Stronger typing, containers, smart-pointers, simple APIs.
chuckadams 16 hours ago [-]
Stroustrup does not write all of his code according to the JSF rules. Avoiding dynamic allocation for example isn't appropriate for all apps, especially if one ends up reinventing it poorly.
One thing he does do consistently, and it baffles me why most other C++ codebases do not, is `using namespace std`. It's the standard library, if there's any names that ought to be used unqualified, it's those.
tialaramex 11 hours ago [-]
The C++ Core Guidelines simultaneously tell you that it's fine to do this and that doing it risks (as so often in C++) weird hard-to-understand compiler errors - because if there's any names that should be unqualified it's your names, not those from the stdlib.
Unlike say, Rust, C++ chooses to just shove most things directly in std. You were probably expecting vector, sort and list and if you're paying attention perhaps integral and format but did you expect get_money? invocable? hive? Because those are all defined too. On average your program probably uses several of these universally reserved identifiers, and more get added in each C++ version. Yay.
agosz 13 hours ago [-]
Maybe I've been doing this for too long, but I don't see why you'd want to stay away from template metaprogramming, especially with the more recent C++ versions. The type traits header makes heavy use of it (so you're probably using it with if constexpr), and C++14/17/20 make it a lot more readable than it used to be.
Panzerschrek 4 hours ago [-]
The true wisdom is to select which exact subset should be used and which avoided.
cogman10 17 hours ago [-]
The only sane usage of C++ is "This is a legacy project, needs to integrate with a legacy C/C++ project, or all our engineers are C++ experts and they don't want a new language".
For everything else, you should pick one of any number of other languages. Rust, swift, zig, go, java, python, javascript. Take your pick.
pjmlp 17 hours ago [-]
Agree, however those other languages will have C++ on their infrastructure maybe forever, due to the costs of fully bootstraping a compiler toolchain and backend support for various kinds of operating systems and processors.
So it is more a kind of gray answer, with polyglot development approach in many cases.
17 hours ago [-]
lordnacho 17 hours ago [-]
Which makes various c++ repos look quite different. It's like learning Arabic and then finding out that you can't actually talk to all the other Arabic speakers.
pjmlp 17 hours ago [-]
Or learning English proper as 2nd language, and then going to Scotland.
Yet we manage.
grg0 14 hours ago [-]
Hoist the sails.
marcosdumay 17 hours ago [-]
I just hope whoever selected the subset knows all of the language, so that they can tell if there's something outside of that subset interfering with it or not.
fukaiall 9 hours ago [-]
C++ feels super natural to me but at the same time it is a miserable fuck due to such odd legacies and ununified features. People literally have spent ages to simply learn those unnecessarily lots of syntaxes rather than solving actual problems. So many compilers and language standards. I do detest those motherfucking Rust fanboys but reasonbly speaking you should choose either C or Rust for low new level projects in 2026.
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.)
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.
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.
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.(except they’re right and you just gained +1 to wisdom)
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!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?!
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.
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..
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.
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.
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”.
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.
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).
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.
Thus you need all mechanisms to implement the same capabilities, thus constructors, by the way they are not alone in this approach.
Also I was under impression that Rust at least has a similar goal?
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().
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.
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.
Sure, but are those "just" characteristics of Rust's current implementation or are those inherent to a constructor-less model in general? The latter is the more interesting question to me in this particular context, and I think it's similar to the question you express.
I think guaranteed in-place initialization is probably the strongest example of something that cannot be expressed through From or Default alone. There are proposals to solve this via traits. I haven't dug deep enough into them, but I'd assume those would be "special" traits that rely on compiler-provided semantics not otherwise expressible in ordinary library code.
Right now, both Box::new() and the vec![] macro resort to compiler intrinsics (write_via_move and write_box_via_move), particularly to avoid unnecessary intermediate storage and excessive stack usage.
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.
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.
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.
Right, see the "I guess the argument might be" part above... I find this to be a very questionable design choice, leaving you to have to go and read a header somewhere to determine whether `Foo f;` is safe or not. But it's not really a choice, is it? C++ had to do it this way to be compatible with how C programs were written back in the 1970s.
> By the way, already in the 16 bit days you could configure to have warnings as errors for variables being used without initialisation.
Ah yes, the "but C can be configured to be not-insane" argument, one of my favorite pjmlp-isms, right up there with "but $LANG's compiler is written in C++" and "but you already get memory safety with a GC". Keep on doing you!
let foo: Goose = Default::default();
Those "primitive" types have a Default, the integers default to zero, as do the floating point types, bool defaults to false, I believe an empty string is the default string (in both the sense that's the default for String, and the default for str, the string slice reference roughly analogous to C++ string_view)
Some things don't have a sane default, just as those things wouldn't provide a zero argument constructor in C++. There isn't a default file descriptor, a default network socket, and so on and so those types do not implement Default
https://www.ralfj.de/blog/2019/07/14/uninit.html
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.
You can unsafely ask for an uninitialized value of any type, but you should not ever assert that you've initialized it unless you actually have. Essentially, you can write this in Rust, but you need to be specific about what you're doing and when you are or are not initializing the variable or else things will go badly for you.
It wouldn't be worse in C++, historically, but C++ people are more used to their world being set on fire by an angry compiler because they did something wrong. In Rust you'd be quite surprised by the compiler's wrath.
† Edited to add: Technically today you do not get this if you call core::mem::uninitialized, because it was so dangerous, instead if you call the deprecated function on a non-ZST - ironically you get a a value scribbled with 0x01 bytes. Doing this ensures in most cases LLVM won't set fire to your program immediately but at a price of doing all that extra work of writing 0x01 bytes. But we did tell you (for several years now) how to do better.
To me the whole point of an "uninitialized variable" is to declare it in one place and then assign it in exactly one code path, which is exactly what rust supports without any unsafe code:
is already perfectly valid, safe rust code, because the compiler knows that all code paths result in assignment before use. And the answer to "what happens on that first line?" is "nothing", because it's just a declaration. In the equivalent C++ you'd be running an arbitrary constructor on the first line, and hoping the compiler optimizes it away. Or if the default constructor doesn't exist or is deleted, you simply can't code that way.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.
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.
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.
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.
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.
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.
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.
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.
If more logic surrounding their construction is needed, you can use factory functions.
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.
Heck, Smalltalk is the original OOP language and has implementation-based inheritance, and construction is done through ordinary methods on class objects.
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.
This is just a single section of the first chapter of a beginner tutorial. And it's already more things to remember than, say, the whole Lua.
I also don't know everything about Java, .NET, Python, JavaScript, SQL, HTML, CSS, and yet work gets done.
To use other languages as example, I bet most folks would fail a pub quiz based on the latest version of those languages, now with about 20 to 40 years history as well.
For what HTML and CSS get used for, the consequences of not knowing everything are fairly low. If it does what you want, it does what you want. Things could maybe be better but they are probably also fine.
SQL is mostly the same though perhaps the performance implications of not knowing it well are higher.
For .NET, Java, and Python things are not much different. If they do what you want, there is probably not much risk that they are doing things you don’t.
JavaScript and, even more dramatically, C++ are quite different. They may be doing what you do not want, or it may be easy for others to make your code do things you do not want. Not understanding the nuance or idiosyncrasies in those languages can do a lot of damage.
Complexity has another angle. If I am working with other people’s Python code, the chance that I will not understand it is low. If I do come across a new feature in .NET or Java, I will spot it right away and will probably be able to research it, learn it, and move on very quickly. Same with HTML and CSS. .NET and CSS are great examples of languages with quite a bit of complexity but where the burden of that complexity is reasonable when maintaining code.
But again, JavaScript and C++ are not that way. C++ code using features I am not familiar with can be a massive burden to unpack and understand. I may not even realize at first that something I do not understand is in play. And, as above, I may not actually understand it as well as I think I do. And that lack of understanding may have surprising consequences.
To your point, A LOT of work still gets done. But perhaps less re-work (so more work) and less risk is possible.
Code quality would be much better in general if everyone actually used "clippy".
Which is anyway a moot point in the age of AI generated code.
They assume the myth that Python is a programming language for beginners and never do a deep dive into what is available.
Worse, due to lack of compatibility across releases, it is rather easy to have code break and be blissful unaware of what a specific point release has changed.
When I learnt Python, the current version was 1.6 and Zope was everywhere, I guess I know a thing or two about its evolution and related complexity.
I think part of the problem is that there are usually 3 different ways to achieve the same semantics, but there would be some subtle technical differences. From my perspective a lot of the problems with C++ come from the incoherent vision for what the language was supposed to be and especially the insistence on backwards compatibility caused significant bloat (design/technical debt) over time.
C++ is (wave hands vigorously) roughly built on top of C's core concepts, so if you know C really well you can (continue waving hands) actually map most of C++'s basic concepts on top of how C works. For example in object methods, the 'this' pointer is actually just silently passed as the first parameter to a function. Class vtables are (at a very abstracted level) just arrays of function pointers. Letting you map those concepts down to a simpler representation like C means C++'s magic starts to lose its magic. Understanding how the class hierarchy is mapped to C can tell you why the 'virtual' keyword exists, and why you need proper copy constructors for those objects but not ones without vtables; and it gives clues for what pure virtual functions are, and why you can't allocate an object with one.
So yeah. Start with C, then figure out the bizarre, incredibly complex maze of abstractions that C++ stacked on top of it.
Use of references for any non nullable pointer.
RAII for heap allocated types, eventually new/delete, leave malloc()/free() family with sizeof type math for interop with existing C code.
Prefer standard library algorithms with proper bounds checking, instead of memsomething and strsomething function family.
Preprocessor magic, when templates and constexpr are type safe, and can even be single stepped on a modern IDE.
Just some examples out of my mind.
[..] One recent real-world example by one of the authors is the following: Improving the following code:
by introducing a getter to have better encapsulation, suddenly caused the undefined behavior:The point being made is that the stumbling blocks exist to be tripped over by the unsuspecting, and are not because of C.
This is also why I dislike the term "C/C++" when referring to them as if they were a single language. They are two distinct languages with substantially different idioms.
What I hate about C++ is that it offers a myriad of ways to accomplish the same thing, ranging from outright terrible to genuinely good. Learning C first can reinforce habits that you'll later have to unlearn.
There is no better way to understand what's going on in std::vector or std::string than writing a growable array in C and having to keep three facts straight: how much storage you own, how many elements you’re using, and who releases it. Knowing how much work the abstraction does is a damn good reason to use it.
First Pascal for those that never coded in their life, and then C++.
The other languages that had explicit learning material were Smalltalk, Caml Light Objective Caml, Prolog, Lisp, Algol, Miranda, Java, PL/SQL, 80x86 and MIPS Assembly.
It was expected that the few classes where C was still used, basically UNIX kernel programming, alongside algorithms and datastructures, the knowledge to code in C would be taken from those C++ classes done during the 2nd year.
So I hold this view for almost 30 something years now.
The more you know about programming in C++, the less confident you become that your code is actually correct, because you've seen before how the most seemingly innocuous decisions turned out to be massive UB footguns. Even worse if you know anything about how computers actually work - that's not relevant, C++ like C targets an abstract virtual machine with semantics unlike any computer ever built.
The simplest example is signed integer overflow: the bright young student knows all about Two's Complement and mistakenly believes all is well, and the wizened but weary mentor must waste everyone's time to avoid summoning nasal demons.
What an unbelievable waste.
cppquiz is a nice test beyond "trivia". There are a few hard questions addressing topics I've never encountered. For example:
```
#include <iostream>
volatile int a;
int main() { std::cout << (a + a); }
```
I would assume that here a is initialised to 0 since it has static lifetime so I'd expect this to just print 0. But the C++ standard specifies that:
> Reading an object designated by a volatile glvalue ([basic.lval]), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression (or a subexpression) in general includes both value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and initiation of side effects. When a call to a library I/O function returns or an access through a volatile glvalue is evaluated the side effect is considered complete, even though some external actions implied by the call (such as the I/O itself) or by the volatile access may not have completed yet.
and if you have side effects unsequenced relative to other side effects (as is the case with operations of the same operand), this is considered UB
Before that you could just read the assembly to know what the code does. Afterwards any compiler update might have change the meaning
https://mikelui.io/img/c++_init_forest.gif
Did you already know that? Do all your junior C++ programmers know that? Do you have lints turned on in every C++ project and dep for that?
Cause I had to really look at it to figure it out. And I had to think, "Would Rust allow this code?"
Sure, it'd be nice if the compiler didn't allow you to write this code. But there are worse examples than this out there.
To reply to GP: many projects specifically avoid the STL.
What's completely unreasonable here is how easy it is for code that looks reasonable in C++ to be deeply dangerous. This is a perfectly normal piece of code, and it looks like the author is even conscientious about nice things like avoiding too many string copies. We shouldn't be out here defending the absolutely unhinged semantics that led to this.
C++ is so extremely hostile that people who try to write good code end up with a very defensive style of programming if they know what they're doing. In my experience, this tends to either almost fully eradicate any performance benefits they were chasing by choosing C++ in the first place, or blow up the time it takes to deliver the product.
The difference between const ref string and string view is one of the first things you learn when you learn about `string view`.
To me, the signature of `Sanitize` is fishy because it's implied that the returned string view is of the const ref string argument. But I agree there are more than one ways to break it.
https://fasterthanli.me/articles/a-rust-match-made-in-hell
Challenge to you, simonask: Explain why the curly braces here determines whether there is a deadlock or not. Bonus points if you do so without asking for help or looking anything up.
https://play.rust-lang.org/?version=stable&mode=debug&editio...
https://play.rust-lang.org/?version=stable&mode=debug&editio...
The curly braces shortens the lifespan of the `MutexGuard` so it gets unlocked before the body of the if-statement. Normally, the temporary used in the if-let pattern lives until the end of the if-statement.
This wouldn't compile if the value guarded by the Mutex wasn't trivially copyable, but it is.
(Note how none of this is UB, just a particularly contrived way to introduce a deadlock.)
But yes, I know that any function with the signature `std::string_view(const std::string&)` or especially `std::string_view(std::string)` is a land mine.
I asked a local LLM to do a code review on it. (gemma4:12b) It flagged the bug, with all caps "THIS WILL CAUSE UNDEFINED BEHAVIOR", and suggested a fix.
C has a much better design with its compound literals having block scope lifetimes.
It gives you one of those fat swiss army knives I had as a kid with a spoon, fork, knife, toothpick, saw, nail trimmer, etc. The problem is it's easy to get dirty and the spoon would get locked in place after one use. But it was there, and it worked (once).
C++ is extremely malleable. I think the reason people like it is very similar to the reason people like lisp. That ability to do horrors like make a lisp interpreter with macros or templates is the charm of C++.
And if you are the only one writing it, it can be a joy because there are few limits to what you can or can't do.
It's only when you have to share a codebase with others that things can get out of hand fast without some committee established usage code and pledge.
my productivity sky rocketed when I switched to Rust.
But C++ allows me to really easily write multithreaded code which I can convince myself is safe :) (and most of the time, is correct, just not on the edge cases). Rust makes that painful.
package management, build system, compiler errors, language simplicity (yes, it adds life times, but removes so many other things), Rust macros, language ergonomics (e.g. match, macros, enums, async, if let, etc.), not having to think about certain things going wrong (including not debugging why things went wrong)
> Rust makes [multithreaded code] painful.
Andreas Kling is switching away from C++ to Rust in Ladybird, because of exactly the reversed experience.
I have been using asynchronous multithreading via tokio - something I never dared to in C++. Alone from the compiler errors I have got doing that, I would assume that I would have been dealing with an unbearable amount of debugging of subtle memory issues.
Well, that's the thing about rust and async. It's far more restrictive (necessarily) than the bounds of safety. The hard problem rust runs into is that async functions can be executed outside of lexical and the lifetime tracking of the rust language. To be absolutely safe, rust ends up needing to assume that async can be executed with no respect to the surrounding lifetimes.
Rust would really benefit from something like structured concurrency in terms of the lifetimes of async functions.
I obviously was not talking about things illegal in safe Rust, which are actually safe, e.g. you cannot send types which are not allowed to be moved across threads across threads in C++ either.
> To be absolutely safe, rust ends up needing to assume that async can be executed with no respect to the surrounding lifetimes.
seems to work with surrounding life times?
https://play.rust-lang.org/?version=stable&mode=debug&editio...
The only way you could think that C++ lets you do everything is if you've never tried anything else.
But the reality is a ton of domains like graphics, video games, and cloud infrastructure is built on C++.
I think the Spanner and Chrome devs “got stuff done” for instance.
I could go on a tangent about the whole “maker vs coder” debate that has sprung up around AI. It feels similar to the C++ idea you’re talking about. The idea is that people who actually understand code and computer science concepts deeply are too busy yak-shaving to be productive like us “makers”.
That ivory tower type definitely exists.
But this false dichotomy seems to be defense mechanism more than anything.
There are smart people that are basically better at everything. They understand C++ deeply, but can code in Python too, build massive pieces of infrastructure like Spanner, and now they are better at driving AI, too.
Not that I’m defending any of the horrible language design decisions of C++. But, you see what I’m saying. People who have skills beyond is in one area aren’t necessarily deficient in another area. Maybe they are just smarter and more skilled than us in a ton of ways.
Yeah, legacy reasons. C++ was a decent-ish improvement over C in the early 90s when many of those APIs were being built out. It's the core language for the Windows API. We didn't get a decent, well supported replacement for C++ until like ten years ago. There's a lotttttttt of legacy C++ code that will stay in use for decades more.
I never said people can't be productive in C++, I'm saying the reason they like it is because it's so hard to use. Just like people can get really good at Dark Souls, people can get really good at C++, too, and they have fun doing it. But I still think that's a con of the language, you can get the same or even better code quality with many modern languages with a much lower bar to mastery.
Followed by the great developer experience of using Turbo Pascal alongside Turbo C++, later Delphi and C++ Builder on RAD Studio.
An experience that many languages still fail to reproduce nowadays, with exception of Java and .NET tooling.
You don't need to master every single feature.
The thing that I like about C++ the most is that it's best language for actually getting things done.
The 'problem' with C++ is that people who want to get things done go to the committee and say, "hey, I need to actually get things done, if you add this language facility, I can actually get things done better," and they'll often just say "ok" and add it to the language. And if you're the sort of person who believes you must use every single facility provided by the language, then you walk away from C++ thinking it's too complicated. But if you're the sort of programmer who's only interested in getting things done, you can simply ignore all that noise and just actually get things done with the facilities that you know and like.
You don't have to use deeply nested templates, complex dynamic inheritance trees, move semantics, Turing-complete template metaprocessing, you don't even have to manually manage your memory if you don't want to. (personally I avoid all of those things except move semantics) But it's there if you need it.
On your initial look, it looks like a total nightmare.
The more you learn and use it, you learn that it is even worse than you ever imagined
So you try something else and find yourself in a constant loop of “if this were c++ i could just go xyz, by nooo”
So then you love it
For example, std::atomic used to default-initialize the underlying value, which led to many bugs in user code. Since C++20 std::atomic uses value-initialization. See https://cplusplus.github.io/LWG/issue2334. On the one hand, std::atomic is now safer to use, on the other hand, it is not an implicit-lifetime-type anymore, which means you can't put it in shared memory without UB...
Another example is glm::vec, which has actually hit me a few times in my own code. At least they recognized the issue and allowed to override the default behavior with the GLM_FORCE_CTOR_INIT define.
Note that if the member is non-trivial, its default constructor is called either way.
C++ rarely pushes the user towards doing the right thing.
Some of these stumped colleagues.
https://imgur.com/forest-gump-c-3wlxtI0
https://leanpub.com/cppinitbook
(I don't know whether it's good or not, I just find it fascinating that it exists)
That’s what Stroustrup does and it works. I just too versatile. Luckily there is recently a push_back against adding new stuff for the sake of it.
My own rules, mine: * Templates are nice. * Template Metaprogramming is not. * Objects and Classes are nice * Inheritance is not.
I like composition and interfaces. I avoid inheritance, aside from some natural cases were it fits (UI Widgets).
I’ve seen in recent years projects switching from C to a mere plain C++. Stronger typing, containers, smart-pointers, simple APIs.
One thing he does do consistently, and it baffles me why most other C++ codebases do not, is `using namespace std`. It's the standard library, if there's any names that ought to be used unqualified, it's those.
Unlike say, Rust, C++ chooses to just shove most things directly in std. You were probably expecting vector, sort and list and if you're paying attention perhaps integral and format but did you expect get_money? invocable? hive? Because those are all defined too. On average your program probably uses several of these universally reserved identifiers, and more get added in each C++ version. Yay.
For everything else, you should pick one of any number of other languages. Rust, swift, zig, go, java, python, javascript. Take your pick.
So it is more a kind of gray answer, with polyglot development approach in many cases.
Yet we manage.