1{{#title std::shared_ptr<T> — Rust ♡ C++}}
2# std::shared\_ptr\<T\>
3
4The Rust binding of std::shared\_ptr\<T\> is called **[`SharedPtr<T>`]**. See
5the link for documentation of the Rust API.
6
7[`SharedPtr<T>`]: https://docs.rs/cxx/*/cxx/struct.SharedPtr.html
8
9### Restrictions:
10
11SharedPtr\<T\> does not support T being an opaque Rust type. You should use a
12Box\<T\> (C++ [rust::Box\<T\>](box.md)) instead for transferring ownership of
13opaque Rust types on the language boundary.
14
15## Example
16
17```rust,noplayground
18// src/main.rs
19
20use std::ops::Deref;
21use std::ptr;
22
23#[cxx::bridge]
24mod ffi {
25    unsafe extern "C++" {
26        include!("example/include/example.h");
27
28        type Object;
29
30        fn create_shared_ptr() -> SharedPtr<Object>;
31    }
32}
33
34fn main() {
35    let ptr1 = ffi::create_shared_ptr();
36
37    {
38        // Create a second shared_ptr holding shared ownership of the same
39        // object. There is still only one Object but two SharedPtr<Object>.
40        // Both pointers point to the same object on the heap.
41        let ptr2 = ptr1.clone();
42        assert!(ptr::eq(ptr1.deref(), ptr2.deref()));
43
44        // ptr2 goes out of scope, but Object is not destroyed yet.
45    }
46
47    println!("say goodbye to Object");
48
49    // ptr1 goes out of scope and Object is destroyed.
50}
51```
52
53```cpp
54// include/example.h
55
56#pragma once
57#include <memory>
58
59class Object {
60public:
61  Object();
62  ~Object();
63};
64
65std::shared_ptr<Object> create_shared_ptr();
66```
67
68```cpp
69// src/example.cc
70
71#include "example/include/example.h"
72#include <iostream>
73
74Object::Object() { std::cout << "construct Object" << std::endl; }
75Object::~Object() { std::cout << "~Object" << std::endl; }
76
77std::shared_ptr<Object> create_shared_ptr() {
78  return std::make_shared<Object>();
79}
80```
81