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 (20)

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

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

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

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

      3. > 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.
        Replies (2)
        1. What is this abomination? This syntactic aversion to my eyes…

          (except they’re right and you just gained +1 to wisdom)

          Replies (1)
          1. The serious answer is it's the ultra-rare aggregate initialization constructor.

            https://en.cppreference.com/cpp/language/aggregate_initializ...

            Generally, when you're doing the

                Foo result;
                result.blah = 7;
            
            pattern, it's because Foo is a struct with only public members and no constructor used for passing data around. e.g.

                struct Foo{
                    int blah;
                    int bar;
                    int snafu;
                }
            
            When it's that simple rather than type out:

                Foo result;
                result.blah = 7;
                result.bar = 6;
                result.snafu = 5;
            
            You'd type:

                Foo result = {.blah = 7, .bar = 6, snafu = 5};
            
            Congrats the code is shorter!
            Replies (1)
            1. It's only rare because it's relatively recent. I expect it to become more widely used because it can be used for simulating named parameters:

                 struct Params { int p1 = 1, p2 = 2, p3 = 3, p4 = 4, p5 = 5; };
                 void foo(Params p) {}
                 int main() {
                   foo({.p2 = 12, .p4 = 14});
                 }
              
              They have to be in the correct order though:

                 // Not allowed
                 foo({.p4 = 14, .p2 = 12});
        2. All young languages try to guarantee it until they don't. zig also fell into this trap.
    2. 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.

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

    4. So Zig makes 'build-in-place' hard?

      That's difficult to believe for a C-like language..

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

        Replies (1)
        1. 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.
    5. As you say C++ needs constructors that are not ordinary functions for things like in-place construction.

      However this is a very bad and unnecessary hack, which I consider as the worst mistake of C++ (already present in the first "C with Classes", before becoming C++).

      The correct solution is to distinguish output parameters from input-output parameters, like e.g. in Ada.

      The difference is that an input-output parameter contains memory on which some object has already been constructed before invoking the function, while an output parameter contains uninitialized memory upon function entry.

      In a language that has 3 parameter types (input, output and input-output), constructors are just ordinary functions that have an output parameter of the type that is constructed. No special treatment for constructors is needed.

      When defining classes, one would have to optionally specify only a default constructor and a destructor, because these must be invoked implicitly by the compiler. Any explicit initialization of an object would use arbitrary functions with suitable parameter types.

      The result parameter of a function should be an output parameter. If an already existing object is passed as an output parameter to a function, inclusively for its result parameter, the compiler would invoke implicitly the destructor for that class, before invoking the function.

      Both output parameters and input-output parameters may be passed either by value or by reference, based on compiler or on ABI choices that are appropriate for their types.

      When output parameters are passed by value, in registers, the compiler will store an output parameter from its register to the desired location, after the function returns, while when input-output parameters are passed by value, in registers, the compiler will load those registers before invoking the function and store them after the function returns.

    6. I feel like this is leaving out the option of only ever referring to objects by a pointer. this means there's no shenanigans around moving or copying things around, and language semantics can still enforce single owners etc. The main disadvantage to this is that it makes any copying explicit, and introduces some (IMO fairly minor) sharp edges around accidentally modifying objects passed into functions etc.
      Replies (1)
      1. It also makes everything heap allocated and prevents dense representations, both of which are not good for performance.
        Replies (1)
        1. Could point to memory from alloca
          Replies (1)
          1. That doesn’t give you the lifetime freedom aspects of the heap, which is what’s required to not think about it.