c++
string赋值为拷贝构造,创建副本,之后能同时用s1、s2
#include <fmt/core.h>
using namespace std;
using namespace fmt;
int main() {
auto s1 = string(25, 'a');
cout << fmt::format("s1: {}", static_cast<void *>(&s1)) << endl;
cout << fmt::format("s1 data: {:p}", s1.c_str()) << endl;
auto s2 = s1;
cout << "assign" << endl;
cout << fmt::format("s1: {}", static_cast<void *>(&s1)) << endl;
cout << fmt::format("s1 data: {:p}", s1.c_str()) << endl;
cout << fmt::format("s2: {}", static_cast<void *>(&s2)) << endl;
cout << fmt::format("s2 data: {:p}", s2.c_str()) << endl;
return 0;
}
s1: 0x16365ffb70
s1 data: 0x1adc6081c00
assign
s1: 0x16365ffb70
s1 data: 0x1adc6081c00
s2: 0x16365ffb50
s2 data: 0x1adc6081c30
rust
string赋值为所有权转移,s1变为不可用
fn main() {
let mut s1 = String::from("hello");
println!("s1: {:p}", &s1);
println!("s1 data: {:p}", s1.as_str());
println!("s1 mut data: {:p}", s1.as_mut_str());
let mut s2 = s1;
println!("assign");
// println!("{:p}", &s1);
println!("s2: {:p}", &s2);
println!("s2 data: {:p}", s2.as_str());
println!("s2 mut data: {:p}", s2.as_mut_str());
}
s1: 0x8ab33af460
s1 data: 0x1c243fcb710
s1 mut data: 0x1c243fcb710
assign
s2: 0x8ab33af560
s2 data: 0x1c243fcb710
s2 mut data: 0x1c243fcb710
如果硬要使用会报错,报错信息友好也是rust的优势之一
error[E0382]: borrow of moved value: `s1`
--> src\main.rs:73:22
|
64 | let mut s1 = String::from("hello");
| ------ move occurs because `s1` has type `String`, which does not implement the `Copy` trait
...
70 | let mut s2 = s1;
| -- value moved here
...
73 | println!("{:p}", &s1);
| ^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
70 | let mut s2 = s1.clone();
| ++++++++