欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > 【CXX】6.6 UniquePtr<T> — std::unique_ptr<T>

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

2025/3/12 21:42:50 来源:https://blog.csdn.net/weixin_43219667/article/details/146177041  浏览:    关键词:【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>();
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词