c++ vs rust string赋值

文章目录


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();
   |                    ++++++++

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值