How does Rust provide move semantics?

前端 未结 4 2131
傲寒
傲寒 2020-11-27 16:24

The Rust language website claims move semantics as one of the features of the language. But I can\'t see how move semantics is implemented in Rust.

Rust boxes are th

4条回答
  •  日久生厌
    2020-11-27 16:52

    In C++ the default assignment of classes and structs is shallow copy. The values are copied, but not the data referenced by pointers. So modifying one instance changes the referenced data of all copies. The values (f.e. used for administration) remain unchanged in the other instance, likely rendering an inconsistent state. A move semantic avoids this situation. Example for a C++ implementation of a memory managed container with move semantic:

    template 
    class object
    {
        T *p;
    public:
        object()
        {
            p=new T;
        }
        ~object()
        {
            if (p != (T *)0) delete p;
        }
        template  //type V is used to allow for conversions between reference and value
        object(object &v)      //copy constructor with move semantic
        {
            p = v.p;      //move ownership
            v.p = (T *)0; //make sure it does not get deleted
        }
        object &operator=(object &v) //move assignment
        {
            delete p;
            p = v.p;
            v.p = (T *)0;
            return *this;
        }
        T &operator*() { return *p; } //reference to object  *d
        T *operator->() { return p; } //pointer to object data  d->
    };
    

    Such an object is automatically garbage collected and can be returned from functions to the calling program. It is extremely efficient and does the same as Rust does:

    object somefn() //function returning an object
    {
       object a;
       auto b=a;  //move semantic; b becomes invalid
       return b;  //this moves the object to the caller
    }
    
    auto c=somefn();
    
    //now c owns the data; memory is freed after leaving the scope
    

提交回复
热议问题