Rust如何提供移动语义? [英] How does Rust provide move semantics?

查看:76
本文介绍了Rust如何提供移动语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生锈的语言网站声称将语义作为语言的特征之一.但是我看不到Rust如何实现移动语义.

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 the only place where move semantics are used.

let x = Box::new(5);
let y: Box<i32> = x; // x is 'moved'

上面的Rust代码可以用C ++编写为

The above Rust code can be written in C++ as

auto x = std::make_unique<int>();
auto y = std::move(x); // Note the explicit move

据我所知(如果我错了,请纠正我)

As far as I know (correct me if I'm wrong),

  • Rust根本没有构造函数,更不用说移动构造函数了.
  • 不支持右值引用.
  • 无法使用rvalue参数创建函数重载.

Rust如何提供移动语义?

How does Rust provide move semantics?

推荐答案

我认为使用C ++时这是一个非常普遍的问题.在C ++中,当涉及到复制和移动时,您将明确地做所有事情.该语言是围绕复制和引用而设计的.使用C ++ 11,可以将移动"内容的功能粘贴到该系统上.另一方面,Rust重新开始.

I think it's a very common issue when coming from C++. In C++ you are doing everything explicitly when it comes to copying and moving. The language was designed around copying and references. With C++11 the ability to "move" stuff was glued onto that system. Rust on the other hand took a fresh start.

Rust根本没有构造函数,更不用说移动构造函数了.

Rust doesn't have constructors at all, let alone move constructors.

您不需要move构造函数. Rust移动了没有副本构造函数"的所有内容,也就是没有实现Copy特征".

You do not need move constructors. Rust moves everything that "does not have a copy constructor", a.k.a. "does not implement the Copy trait".

struct A;

fn test() {
    let a = A;
    let b = a;
    let c = a; // error, a is moved
}

Rust的默认构造函数(按照惯例)只是一个名为new的关联函数:

Rust's default constructor is (by convention) simply an associated function called new:

struct A(i32);
impl A {
    fn new() -> A {
        A(5)
    }
}

更复杂的构造函数应具有更多可表达的名称.这是C ++中命名的构造函数惯用法

More complex constructors should have more expressive names. This is the named constructor idiom in C++

不支持右值引用.

No support for rvalue references.

它一直是人们所要求的功能,请参见 RFC问题998 ,但是您最有可能要求提供其他功能:将内容移至功能:

It has always been a requested feature, see RFC issue 998, but most likely you are asking for a different feature: moving stuff to functions:

struct A;

fn move_to(a: A) {
    // a is moved into here, you own it now.
}

fn test() {
    let a = A;
    move_to(a);
    let c = a; // error, a is moved
}


无法创建带有rvalue参数的函数重载.

No way to create functions overloads with rvalue parameters.

您可以使用特征来做到这一点.

You can do that with traits.

trait Ref {
    fn test(&self);
}

trait Move {
    fn test(self);
}

struct A;
impl Ref for A {
    fn test(&self) {
        println!("by ref");
    }
}
impl Move for A {
    fn test(self) {
        println!("by value");
    }
}
fn main() {
    let a = A;
    (&a).test(); // prints "by ref"
    a.test(); // prints "by value"
}

这篇关于Rust如何提供移动语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆