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

  1. These aren’t problems with the constructors per se, though. E.g. Java doesn’t have any of these problems.
    Replies (1)
    1. Java absolutely does have the ambiguous overload problem.

          public class MyVector {
              public MyVector(int... items) {
                  System.out.println(String.format("constructing a vector of %d items", items.length));
              }
      
              public MyVector(int start, int end) {
                  System.out.println(String.format("constructing a vector from the range [%d, %d)", start, end));
              }
          }
      
      How do you construct a MyVector of two items?

      In JavaScript, how do you use new Array(...) to create an array consisting of a single integer? You can do the same with a single value of any other type.

      The reason these languages don't have the make_unique or emplace problems is because they don't have a concept of in-place construction at all, since objects in those languages are heap-allocated and have reference semantics anyway.

      Replies (2)
      1. Right, but that’s a relatively rare problem, and doesn’t usually result in crashes.

        More importantly, you have exactly the same problem if you overload a regular method that way. So it’s a problem with overloading, not with constructors.

        > How do you construct a MyVector of two items?

            new MyVector(new int[] { 23, 42 })
        
        The correct solution, of course, is to provide named static constructor methods instead (e.g. `MyVector.ofRange(start, end)`).

        I do agree that support for named actual constructor methods would be nice. But they would still be constructors.

      2. It’s ambiguous to the reader, but the JLS strictly defines which constructor would be called here. It’s the int a, int b constructor.