summaryrefslogtreecommitdiffstats
path: root/vendor/cxx/book/src/binding/uniqueptr.md
blob: eefbc34a39d2f56c1491b5e57f198c1392e89870 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
{{#title std::unique_ptr<T> — Rust ♡ C++}}
# std::unique\_ptr\<T\>

The Rust binding of std::unique\_ptr\<T\> is called **[`UniquePtr<T>`]**. See
the link for documentation of the Rust API.

[`UniquePtr<T>`]: https://docs.rs/cxx/*/cxx/struct.UniquePtr.html

### Restrictions:

Only `std::unique_ptr<T, std::default_delete<T>>` is currently supported. Custom
deleters may be supported in the future.

UniquePtr\<T\> does not support T being an opaque Rust type. You should use a
Box\<T\> (C++ [rust::Box\<T\>](box.md)) instead for transferring ownership of
opaque Rust types on the language boundary.

## Example

UniquePtr is commonly useful for returning opaque C++ objects to Rust. This use
case was featured in the [*blobstore tutorial*](../tutorial.md).

```rust,noplayground
// 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();
```

```cpp
// src/blobstore.cc

#include "example/include/blobstore.h"

std::unique_ptr<BlobstoreClient> new_blobstore_client() {
  return std::make_unique<BlobstoreClient>();
}
```