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

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

    2. Rust doesn’t have implementation inheritance. If it did, it would need a constructor-like concept as well.
      Replies (1)
      1. With guaranteed RVO you could do something like this (pseudo-C):

           struct FooBase { ... }
           fn make_foo_base(...) -> FooBase
           struct Foo { base : FooBase; ... }
           fn make_foo(args...) -> Foo {
              return { .base = make_foo_base(...), ... }
           }
        Replies (1)
        1. How is it ensured that make_foo will actually call make_foo_base?
          Replies (2)
          1. You are right, sorry, lost track or the thread.
          2. Because it needs a FooBase to give as the value for .base or the struct initialization isn't valid because it doesn't give values for all the members?