Unofficial Hacker News companion — get notified on comment replies, and more.

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

131 points by surprisetalk 7 days ago | lemire.me | 202 comments on HN | Vote on HN (opens Hacker News) |

View full thread · View on Hacker News

Comment thread (1)

  1. Yep, that's std::mem::zeroed(), which just writes zeroes into the allocated memory regardless of its type... also only available in unsafe code.

        #[derive(Debug)]
        struct Foo {
            _i: i32,
        }
    
        fn main() {
            let x: i32 = unsafe { std::mem::zeroed() };
            println!("x={x}");
            let f: Foo = unsafe { std::mem::zeroed() };
            println!("f={f:?}");
        }
    
    prints:

        x=0
        f=Foo { _i: 0 }
    
    It's unsafe because if Foo contained a String, it would be string with a null pointer inside it and you'd crash trying to read it. If you want "Default" values instead of zeroed (ie. you don't want to run unsafe code), that's what the Default trait is for, and this becomes:

        #[derive(Debug, Default)]
        struct Foo {
            _i: i32,
        }
    
        fn main() {
            let x: i32 = Default::default();
            println!("x={x}");
            let f: Foo = Default::default();
            println!("f={f:?}");
        }
    
    and prints the same thing.