An unofficial, read-only Hacker News reader. Join the beta →

In C++, = default and {} are not the same constructor (opens external site)

129 points by surprisetalk 2 days ago | lemire.me | 198 comments on HN

View full thread · View on Hacker News

Comment thread (72)

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

    Replies (10)
    1. 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.
      Replies (1)
      1. I hope everyone is doing static analysis!
    2. C++ dev here. I love this mess of a language ..
      Replies (5)
      1. Yes, people even have a term for this. It's named after a Swedish city.
      2. 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?"

        Replies (3)
        1. 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.

          Replies (2)
          1. 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.

            Replies (2)
            1. 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.

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

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

              Continue this thread (1 replies) →

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

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

        3. I mean, you could just turn warnings on: https://godbolt.org/z/ns6cb9T6q

          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.

      3. 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.
        Replies (5)
        1. 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.

          Replies (2)
          1. > 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.

            Replies (2)
            1. 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.

              Continue this thread (1 replies) →

            2. Game developers can't say the same though.
          2. Yes, C++ is an omnibus language where all things are possible.
            Replies (1)
            1. 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.

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

          Replies (1)
          1. > 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.

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

        4. 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.
        5. > 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.

      4. Stockholm syndrome we're all vulnerable to. I love bash for instance.
      5. 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

        Replies (1)
        1. This roughly sums up my feelings. C++ is horrendous, but it's also the best tool I have.
    3. 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.
      Replies (1)
      1. This. Prudent to stay out of the minefield sums it up perfectly. My only conclusion about why some still argue for building more routes through the minefield is that C++ has a literal cult of followers and promoters... and it's sooo hard to actually leave a cult. It was hard for me too, having started C++ in 1992...
    4. lol

          int x = 5;
          int x {5};
          int x = {5}
          int x (5);
    5. 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?
      Replies (4)
      1. It's not expert friendly either. The Stockholm syndrome just kicks in.
        Replies (2)
        1. The more you know about C++, the less you're confident about how your code will be compiled.
          Replies (1)
          1. 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.
        2. 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.

          Replies (1)
          1. 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

            Replies (1)
            1. In practice, it will be 0, assuming no external modification of a. Strictly under standard, its UB.

              Continue this thread (1 replies) →

      2. 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).
        Replies (1)
        1. Tour of C++, last edition, would be a good one.
      3. 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.

        Replies (1)
        1. This will only bring bad practices in modern C++, the root of all C/C++ discussions in security reports.
          Replies (3)
          1. 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.
            Replies (2)
            1. 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.

              Continue this thread (1 replies) →

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

          2. 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.
            Replies (1)
            1. 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.
          3. 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.

            Replies (1)
            1. 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.

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

    6. My favourite programming gif is relevant here I think

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

      Replies (1)
      1. I went through this thread looking for this so because it would be absolutely criminal if it weren't included here by someone.
    7. 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.

      Replies (2)
      1. 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.
        Replies (1)
        1. 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.

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

        Replies (1)
        1. 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.

    8. 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.
    9. 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.
    10. 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.
      Replies (1)
      1. 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