当前位置: 首页 > wzjs >正文

西安企业网站制作公司微信开发者中心

西安企业网站制作公司,微信开发者中心,东营市招投标信息网,企业管理咨询收费方案明细文章目录 第四章:Ownership 所有权核心概念关键机制引用与借用(Reference & Borrowing)悬垂引用问题错误示例分析解决方案引用安全规则 切片(Slice)内存安全保证 第四章:Ownership 所有权 Ownership i…

文章目录

  • 第四章:Ownership 所有权
    • 核心概念
    • 关键机制
    • 引用与借用(Reference & Borrowing)
      • 悬垂引用问题
        • 错误示例分析
        • 解决方案
        • 引用安全规则
    • 切片(Slice)
    • 内存安全保证

第四章:Ownership 所有权

Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector.

核心概念

所有权三原则:

  • 每个值有且只有一个所有者
  • 所有权可转移(move)
  • 所有者离开作用域时值自动释放(drop)
  • Each value in Rust has a variable that’s called its owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.

内存管理:

  • 栈(Stack):固定大小数据,高效自动管理
  • 堆(Heap):动态大小数据,需显式分配

Example:

fn main() {let mut s = String::from("hello");s.push_str(", world!"); // push_str() appends a literal to a Stringprintln!("{}", s); // This will print `hello, world!`
}

Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes called Resource Acquisition Is Initialization (RAII). The drop function in Rust will be familiar to you if you’ve used RAII patterns.

关键机制

  • 移动语义(Move):

    • 赋值操作默认转移所有权(非浅拷贝)
    • 原变量随即失效,防止悬垂指针
    let s1 = String::from("hello");
    let s2 = s1;  // s1所有权转移至s2,s1失效
    

    If you’ve heard the terms shallow copy and deep copy while working with other languages, the concept of copying the pointer, length, and capacity without copying the data probably sounds like making a shallow copy. But because Rust also invalidates the first variable, instead of being called a shallow copy, it’s known as a move. In this example, we would say that s1 was moved into s2.
    在这里插入图片描述
    Rust will never automatically create “deep” copies of your data. Therefore, any automatic copying can be assumed to be inexpensive in terms of runtime performance.

  • 克隆(Clone):

    • 显式深度拷贝堆数据
    let s1 = String::from("hello");
    let s2 = s1.clone();  // 完整拷贝数据
    

    When you see a call to clone, you know that some arbitrary code is being executed and that code may be expensive. It’s a visual indicator that something different is going on.
    在这里插入图片描述

  • Copy trait:

    • 标量类型(整数、布尔值等)自动实现
    • 赋值时执行位拷贝而非所有权转移
    • 与Drop trait互斥

引用与借用(Reference & Borrowing)

  • 不可变引用:

    • 允许多个同时存在
    • 禁止修改数据
    fn calculate_length(s: &String) -> usize {s.len()
    }
    
  • 可变引用:

    • 独占性:同一作用域只能存在一个
    • 数据竞争预防
    fn change(s: &mut String) {s.push_str(", world");
    }
    

悬垂引用问题

悬垂引用(Dangling Reference)是指指针指向的内存已经被释放但指针仍然存在的情况,这是内存安全的重大威胁。

错误示例分析
fn dangle() -> &String {  // 尝试返回字符串引用let s = String::from("hello");  // 创建局部变量&s  // 返回局部变量的引用
}  // s离开作用域被释放,返回的引用变成悬垂指针

编译器会阻止这段代码编译,错误提示:

error[E0106]: missing lifetime specifier
解决方案
  1. 转移所有权
fn no_dangle() -> String {  // 直接返回String(转移所有权)let s = String::from("hello");s  // 所有权转移给调用者
}
  1. 使用静态生命周期
fn get_static_str() -> &'static str {"hello"  // 字符串字面量有'static生命周期
}
引用安全规则
  1. 可变性独占原则:
  • 任意时刻,一个数据要么:
    • 有唯一的可变引用(&mut T)
    • 或有多个不可变引用(&T)
  • 二者不可同时存在
  1. 生命周期保证:
  • 所有引用必须始终有效

  • 编译器通过生命周期检查确保:

    fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {if x.len() > y.len() { x } else { y }
    }
    

切片(Slice)

  • 字符串切片:
    • 安全视图,不获取所有权
    let s = String::from("hello world");let hello = &s[0..5];
    let world = &s[6..11];
    
  • 通用原则:
    • 编译时保证引用有效性
    • 自动边界检查防止越界访问

在这里插入图片描述

内存安全保证

所有权系统在编译期实现:

  • 自动内存回收(RAII模式)
  • 无数据竞争
  • 无悬垂指针
  • 零运行时开销

这套机制使Rust无需垃圾回收器即可保证内存安全,同时保持与C/C++相当的性能。

The concepts of ownership, borrowing, and slices ensure memory safety in Rust programs at compile time. The Rust language gives you control over your memory usage in the same way as other systems programming languages, but having the owner of data automatically clean up that data when the owner goes out of scope means you don’t have to write and debug extra code to get this control.


文章转载自:

http://eQXbHImn.qbfkz.cn
http://VyK4EImr.qbfkz.cn
http://hqxzQHaM.qbfkz.cn
http://mSksG70Z.qbfkz.cn
http://HbwdewtH.qbfkz.cn
http://i6PFCG0k.qbfkz.cn
http://JWHu3d72.qbfkz.cn
http://zUvtJDlg.qbfkz.cn
http://En7arP2c.qbfkz.cn
http://VdhoB7OX.qbfkz.cn
http://F2FZSNdZ.qbfkz.cn
http://ki3owq7H.qbfkz.cn
http://tcnTVD0H.qbfkz.cn
http://SJJHITrZ.qbfkz.cn
http://P41F4G5h.qbfkz.cn
http://v2rp8p0a.qbfkz.cn
http://hUvIvukL.qbfkz.cn
http://4N66x5mj.qbfkz.cn
http://dIHaL4AA.qbfkz.cn
http://jaczLVsl.qbfkz.cn
http://Jx2f5NvA.qbfkz.cn
http://qkGSEnZI.qbfkz.cn
http://DuMdkPxW.qbfkz.cn
http://3cn0xKmf.qbfkz.cn
http://WQOuDyAa.qbfkz.cn
http://YRGXDtk2.qbfkz.cn
http://TG2aMWXF.qbfkz.cn
http://SFBNpvcn.qbfkz.cn
http://2vS4SCxB.qbfkz.cn
http://N2iFVoNh.qbfkz.cn
http://www.dtcms.com/wzjs/672262.html

相关文章:

  • 教育培训网站建设ppt模板wordpress防止被镜像
  • 网站建设 2018门户网站建设汇报
  • 安卓手机网站开发工具wordpress文章推荐系统
  • 站长之家最新网站大学网站开发策划
  • 顺德做网站wordpress如何增加导航栏
  • 网天下信息技术有限公司网站食品包装设计要求规范
  • 清新县城乡规划建设局网站网站建设与管理工资
  • 网站的结构是什么样的网站用哪个数据库
  • 福建省效能建设网站电销做网站项目
  • cms建站模板app重庆网站建设技术外包
  • 商派商城网站建设二次开发做网站和网络推广
  • 手机网站制作哪家公司好深入浅出wordpress pdf
  • 网站建设原则乔拓云网微信小程序制作
  • 成都网站seo网站制作 电子商城
  • 河北网站建设模板互联网推广公司
  • 做网站数据库坏了网站设计行业前景
  • 网站建设专员一定要会网站建设吗做一款app需要网站吗
  • php网站开发项目经验如何写做网站空间多大
  • 济南做外贸网站的公司网架公司名字推荐大全
  • 网站注册商是什么电商网站建设可行性分析
  • 杭州开发区建设局网站做任务的奖金网站
  • jsp 淘宝网站验证码 设计经典企业网站
  • python购物网站开发流程网站建设与开发的软件
  • 有没有可以做游戏的网站卖东西专业网站网上
  • 指示灯具网站建设wordpress footer 修改
  • 湘潭网站建设 要上磐石网络官网最新版cmsv6
  • 模板网站会员阿里云如何购买域名
  • 广州家居网站设计wordpress屏蔽蜘蛛爬虫
  • 视频网站开发的难点寮步镇网站仿做
  • 咸阳网站建设seo烟台做网站哪家好