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

【CXX】6.6 UniquePtr<T> — std::unique_ptr<T>

std::unique_ptr 的 Rust 绑定称为 UniquePtr。有关 Rust API 的文档,请参见链接。

限制:

目前仅支持 std::unique_ptr<T, std::default_delete>。未来可能会支持自定义删除器。

UniquePtr 不支持 T 为不透明的 Rust 类型。对于在语言边界传递不透明 Rust 类型的所有权,应使用 Box(C++ 中的 rust::Box)。

示例:

UniquePtr 通常用于将不透明的 C++ 对象返回给 Rust。此用例在 blobstore 教程中有所体现。

// src/main.rs

#[cxx::bridge]
mod ffi {
    unsafe extern "C++" {
        include!("example/include/blobstore.h");

        type BlobstoreClient;

        fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
        // ...
    }
}

fn main() {
    let client = ffi::new_blobstore_client();
    // ...
}
// include/blobstore.h

#pragma once
#include <memory>

class BlobstoreClient;

std::unique_ptr<BlobstoreClient> new_blobstore_client();

// src/blobstore.cc

#include "example/include/blobstore.h"

std::unique_ptr<BlobstoreClient> new_blobstore_client() {
  return std::make_unique<BlobstoreClient>();
}

http://www.kler.cn/a/581800.html

相关文章:

  • 深入理解 Rust 中的模式匹配语法
  • SpringBoot(1)——创建SpringBoot项目的方式
  • rom定制系列------小米note3 原生安卓15 批量线刷 默认开启usb功能选项 插电自启等
  • Java中数据库索引选择B+树而非红黑树的详细解析
  • DeepSeek引领端侧AI革命,边缘智能重构AI价值金字塔
  • Spring Boot中@Valid 与 @Validated 注解的详解
  • c++-------------------智能指针
  • 途游游戏25届AI算法岗内推
  • 2024华为OD机试真题-日志排序(C++)-E卷-100分
  • AttributeError: module ‘backend_interagg‘ has no attribute ‘FigureCanvas‘
  • Android Compose MutableInteractionSource介绍
  • 工程化与框架系列(28)--前端国际化实现
  • TDengine作为存储有什么缺点
  • 数据库之PostgreSQL详解(待补充)
  • Websocket的基本使用
  • 使用 React 和 Ant Design 处理 Excel 和 CSV 文件
  • upload-labs-master通关攻略(1~4)
  • 本地部署 OpenManus 保姆级教程(Windows 版)
  • C语言零基础入门教程(1)
  • 关于sqlalchemy的ORM的使用