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

【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>();
}

相关文章:

  • Windows安装milvus和图形化管理工具attu
  • 【webrtc debug tools】 rtc_event_log_to_text
  • 大数据面试之路 (一) 数据倾斜
  • 第一章:介绍Python编程-1.Python是什么
  • 2.2 企业级ESLint/Prettier规则定制
  • Excel两列和依次相减
  • AnyAnomaly: 基于大型视觉语言模型的零样本可定制视频异常检测
  • 中断机制及NVIC管理解析
  • Xavier 初始化:深度网络权重初始化的经典之作
  • Java小白-管理项目工具Maven(2)初识Maven
  • Cursor配置Golang开发环境
  • Java变量与常量
  • ubuntu 22.04 本地部署DeepSeek的Janus Pro
  • BigFoot EventAlertMod lua
  • 【hot100】046全排列
  • 初识数组下篇
  • 滑动窗口及边缘化直观理解
  • Maven 的常用指令
  • 编程视界:C++命名空间
  • 人工智能之数学基础:坐标变换
  • 梅花奖在上海|朱洁静:穿越了人生暴风雨,舞台是最好良药
  • 婚姻登记“全国通办”首日,上海虹口登记中心迎来“甜蜜高峰”
  • 墨西哥宣布就“墨西哥湾”更名一事起诉谷歌
  • 马上评丨规范隐藏式车门把手,重申安全高于酷炫
  • 第32届梅花奖终评启幕,上海京剧院《智取威虎山》满堂彩
  • 北京:下调个人住房公积金贷款利率