In C++, = default and {} are not the same constructor (lemire.me)

54 points by surprisetalk 4 hours ago

ninkendo 3 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.)

layer8 an hour 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), and also must not be able to see an uninitialized superclass instance; 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 set the object to an incorrect 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 24 minutes 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.

Calavar 3 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 2 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):

   Foo make_foo() {
      Foo result;
      result.blah = 7;
      return result;
   } 
   Foo f = make_foo();
   
   // Equivalent to:
   Foo f;
   f.blah = 7;
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 2 hours ago

jjmarr 35 minutes ago

kpw94 an hour ago

ninkendo 34 minutes 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.

stackghost 2 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.

pwdisswordfishq 27 minutes 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 in the presence of constructors 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 9 minutes 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.

layer8 24 minutes ago

These aren’t problems with the constructors per se, though. E.g. Java doesn’t have any of these problems.

pwdisswordfishq 10 minutes ago

quietbritishjim 3 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).

pjmlp 3 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 3 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 3 hours ago

ninkendo 3 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 3 hours ago

William_BB 2 hours ago

lefty2 2 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.

marcosdumay 3 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 3 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 an hour ago

badpun an hour 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.

binary132 3 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 2 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 21 minutes ago

raincole 3 hours ago

No language scares me like C++ does. Look at this page: https://www.learncpp.com/cpp-tutorial/variable-assignment-an...

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 an hour 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 3 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 3 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 2 hours ago

kstrauser 3 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 3 hours ago

tolugenius 3 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?

William_BB 3 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 3 hours ago

coldpie 3 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 3 hours ago

sobellian 3 hours ago

It's not expert friendly either. The Stockholm syndrome just kicks in.

simonask 44 minutes ago

bestouff 3 hours ago

aleksiy123 3 hours ago

My favourite programming gif is relevant here I think

https://mikelui.io/img/c++_init_forest.gif

saghm 3 hours ago

I went through this thread looking for this so because it would be absolutely criminal if it weren't included here by someone.

chuckadams 3 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.

apples_oranges 3 hours ago

C++ dev here. I love this mess of a language ..

01HNNWZ0MV43FF 3 hours ago

Did you see the "Spooky C++" post? https://www.nablag.com/spooky_cpp

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?"

nwallin a minute ago

William_BB 3 hours ago

cv5005 an hour ago

lkjdsklf 3 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 3 hours ago

coldpie 3 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 3 hours ago

materielle 3 hours ago

trealira an hour ago

pjmlp 3 hours ago

gchamonlive 3 hours ago

Stockholm syndrome we're all vulnerable to. I love bash for instance.

raincole 3 hours ago

Yes, people even have a term for this. It's named after a Swedish city.

CamperBob2 3 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 3 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 3 hours ago

I hope everyone is doing static analysis!

fnord77 3 hours ago

lol

    int x = 5;
    int x {5};
    int x = {5}
    int x (5);

spacechild1 2 hours ago

The example is pretty contrived because in practice you'd want to zero-initialize the members in the default constructor anyway.

    struct span {
        const char *p = nullptr;
        size_t len = 0;
        span() = default; // or span() {}
        span(const char *s, size_t n) : p(s), len(n) {}
    };
In that case, there is no difference between

    span s;
and

    span s{};
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.

jacobcmarshall 26 minutes 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.

BiraIgnacio 7 minutes ago

jeffbee 29 minutes ago

Which is of no consequence to LLVM

vinyl7 3 hours ago

The only sane usage of C++ is to only use a very small subset of its features.

ho_schi 3 hours ago

https://www.stroustrup.com/JSF-AV-rules.pdf

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 2 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.

cogman10 3 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 3 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.

lordnacho 3 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 3 hours ago

Or learning English proper as 2nd language, and then going to Scotland.

Yet we manage.

grg0 3 minutes ago

marcosdumay 3 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.