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

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