【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 教程中有所体现。

rust 复制代码
// 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();
    // ...
}
cpp 复制代码
// 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>();
}
相关推荐
charlie1145141912 小时前
精读C++20设计模式:行为型设计模式:中介者模式
c++·学习·设计模式·c++20·中介者模式
楼田莉子2 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
oioihoii3 小时前
超越 std::unique_ptr:探讨自定义删除器的真正力量
c++
Gohldg3 小时前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法
天若有情6733 小时前
C++空值初始化利器:empty.h使用指南
开发语言·c++
远远远远子3 小时前
类与对象 --1
开发语言·c++·算法
无敌最俊朗@4 小时前
C/C++ 关键关键字面试指南 (const, static, volatile, explicit)
c语言·开发语言·c++·面试
利刃大大4 小时前
【高并发服务器】三、正则表达式的使用
服务器·c++·正则表达式·项目
小何好运暴富开心幸福6 小时前
C++之再谈类与对象
开发语言·c++·vscode
郝学胜-神的一滴6 小时前
中秋特别篇:使用QtOpenGL和着色器绘制星空与满月
开发语言·c++·算法·软件工程·着色器·中秋