1{{#title std::unique_ptr<T> — Rust ♡ C++}} 2# std::unique\_ptr\<T\> 3 4The Rust binding of std::unique\_ptr\<T\> is called **[`UniquePtr<T>`]**. See 5the link for documentation of the Rust API. 6 7[`UniquePtr<T>`]: https://docs.rs/cxx/*/cxx/struct.UniquePtr.html 8 9### Restrictions: 10 11Only `std::unique_ptr<T, std::default_delete<T>>` is currently supported. Custom 12deleters may be supported in the future. 13 14UniquePtr\<T\> does not support T being an opaque Rust type. You should use a 15Box\<T\> (C++ [rust::Box\<T\>](box.md)) instead for transferring ownership of 16opaque Rust types on the language boundary. 17 18## Example 19 20UniquePtr is commonly useful for returning opaque C++ objects to Rust. This use 21case was featured in the [*blobstore tutorial*](../tutorial.md). 22 23```rust,noplayground 24// src/main.rs 25 26#[cxx::bridge] 27mod ffi { 28 unsafe extern "C++" { 29 include!("example/include/blobstore.h"); 30 31 type BlobstoreClient; 32 33 fn new_blobstore_client() -> UniquePtr<BlobstoreClient>; 34 // ... 35 } 36} 37 38fn main() { 39 let client = ffi::new_blobstore_client(); 40 // ... 41} 42``` 43 44```cpp 45// include/blobstore.h 46 47#pragma once 48#include <memory> 49 50class BlobstoreClient; 51 52std::unique_ptr<BlobstoreClient> new_blobstore_client(); 53``` 54 55```cpp 56// src/blobstore.cc 57 58#include "example/include/blobstore.h" 59 60std::unique_ptr<BlobstoreClient> new_blobstore_client() { 61 return std::make_unique<BlobstoreClient>(); 62} 63``` 64