• [^] # Re: Rust vs Go

    Posté par (site web personnel) . En réponse à la dépêche Rust s’oxyde en version 0.10. Évalué à 10.

    Dire que la gestion manuelle de la mémoire est «unsafe», c'est vraiment un truc à la mode ces dernières années. [...] Qu'est-ce qu'on reproche encore à C++ à ce niveau ? Des fantasmes sans doute. Le C++ n'est pas du C !

    #include <memory>
    #include <iostream>
    int const &get_one()
    {
     std::unique_ptr<int> i(new int(1));
     return *i;
    }
    int main()
    {
     std::cout << get_one() << std::endl;
     return 0;
    }

    Ça a l'air par mal, compilons voir avec tous pleins de warning

    $ clang++ --std=c++11 -Weverything -Wno-c++98-compat -Wno-missing-prototypes test.cpp -o test
    $ 
    

    cool ça a l'air memory safe ! On teste ?

    $ valgrind ./test
    ==8446== Memcheck, a memory error detector
    ==8446== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
    ==8446== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
    ==8446== Command: ./test
    ==8446== 
    ==8446== Invalid read of size 4
    ==8446== at 0x400BAC: main (in /.../test)
    ==8446== Address 0x59f8040 is 0 bytes inside a block of size 4 free'd
    ==8446== at 0x4C28BDC: operator delete(void*) (vg_replace_malloc.c:502)
    ==8446== by 0x400DC0: std::default_delete<int>::operator()(int*) const (in /.../test)
    ==8446== by 0x400D25: std::unique_ptr<int, std::default_delete<int> >::~unique_ptr() (in /.../test)
    ==8446== by 0x400C44: std::unique_ptr<int, std::default_delete<int> >::~unique_ptr() (in /.../test)
    ==8446== by 0x400B69: get_one() (in /.../test)
    ==8446== by 0x400BA3: main (in /.../test)
    ==8446== 
    1
    ==8446== 
    ==8446== HEAP SUMMARY:
    ==8446== in use at exit: 0 bytes in 0 blocks
    ==8446== total heap usage: 1 allocs, 1 frees, 4 bytes allocated
    ==8446== 
    ==8446== All heap blocks were freed -- no leaks are possible
    ==8446== 
    ==8446== For counts of detected and suppressed errors, rerun with: -v
    ==8446== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
    $ 
    

    Oups !

    La même chose en rust

    fn get_one() -> &int {
     return &*~1;
    }
    fn main() {
     println!("{}", *get_one());
    }

    On compile :

    $ rustc test.rs -o test
    test.rs:2:12: 2:16 error: borrowed value does not live long enough
    test.rs:2 return &*~1;
     ^~~~
    test.rs:1:22: 3:2 note: reference must be valid for the anonymous lifetime #1 defined on the block at 1:21...
    test.rs:1 fn get_one() -> &int {
    test.rs:2 return &*~1;
    test.rs:3 }
    test.rs:2:5: 2:16 note: ...but borrowed value is only valid for the statement at 2:4
    test.rs:2 return &*~1;
     ^~~~~~~~~~~
    error: aborting due to previous error
    $
    

    Ha, ça compile pas, en effet.