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