An unofficial, read-only Hacker News reader.

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

130 points by surprisetalk 3 days ago | lemire.me | 198 comments on HN

View full thread · View on Hacker News

Comment thread (15)

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

          Replies (1)
          1. 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
            Replies (2)
            1. Why not simply write the following?

                 const Config config { loadConfig() };
                 for (auto &name : config.names) {
                     use(name);
                 }
              
              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.

              Continue this thread (1 replies) →

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

              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.