Why is it legal to take temporary?

Based on C ++, I'm pretty surprised that this code is valid in Rust:

let x = &mut String::new();
x.push_str("Hello!");

In C ++, you cannot take the address of the temporary, and the temporary will not survive the expression in which it appeared.

How long has it lived temporarily in rust? And since it xis only borrowed, who owns the line?

+4
source share
2 answers

Why is it legal to lend a temporary?

This is legal for the same reason that it is illegal in C ++ - because someone said it should be .

How long has it lived temporarily in rust? And since it xis only borrowed, who owns the line?

Link says :

time life time usually

  • innermost expression; the tail expression of a block is considered part of the instruction that includes the block, or
  • , if if/else loop while.

rvalue, let, , , (let) ( , ). , , let .

, :

let mut a_variable_you_cant_see = String::new();
let x = &mut a_variable_you_cant_see;
x.push_str("Hello!");

. :

+10

Rust MIR ; :

fn main() {
    let foo = &String::new();
}

MIR, ( ):

fn main() -> () {
    let mut _0: ();
    scope 1 {
        let _1: &std::string::String; // the reference is declared
    }
    scope 2 {
    }
    let mut _2: std::string::String; // the owner is declared

    bb0: {                              
        StorageLive(_1); // the reference becomes applicable
        StorageLive(_2); // the owner becomes applicable
        _2 = const std::string::String::new() -> bb1; // the owner gets a value; go to basic block 1
    }

    bb1: {
        _1 = &_2; // the reference now points to the owner
        _0 = ();
        StorageDead(_1); // the reference is no longer applicable
        drop(_2) -> bb2; // the owner value is dropped; go to basic block 2
    }

    bb2: {
        StorageDead(_2); // the owner is no longer applicable
        return;
    }
}

, "" , , , .

, , -, scope 2 - ; , MIR 100%.

+5

Source: https://habr.com/ru/post/1690288/


All Articles