| 1 | #include <memory> |
|---|---|
| 2 | #include <string> |
| 3 | |
| 4 | struct User { |
| 5 | int id = 30; |
| 6 | std::string name = "steph"; |
| 7 | }; |
| 8 | |
| 9 | struct NodeU { |
| 10 | std::unique_ptr<NodeU> next; |
| 11 | int value; |
| 12 | }; |
| 13 | |
| 14 | // libc++ stores unique_ptr data in a compressed pair, which has a specialized |
| 15 | // representation when the type of the second element is an empty class. So |
| 16 | // we need a deleter class with a dummy data member to trigger the other path. |
| 17 | struct NonEmptyIntDeleter { |
| 18 | void operator()(int *ptr) { delete ptr; } |
| 19 | |
| 20 | int dummy_ = 9999; |
| 21 | }; |
| 22 | |
| 23 | static void recursive() { |
| 24 | // Set up a structure where we have a loop in the unique_ptr chain. |
| 25 | NodeU *f1 = new NodeU{.next: nullptr, .value: 1}; |
| 26 | NodeU *f2 = new NodeU{.next: nullptr, .value: 2}; |
| 27 | f1->next.reset(p: f2); |
| 28 | f2->next.reset(p: f1); |
| 29 | std::puts(s: "Set break point at this line."); |
| 30 | } |
| 31 | |
| 32 | int main() { |
| 33 | std::unique_ptr<int> up_empty; |
| 34 | std::unique_ptr<int> up_int = std::make_unique<int>(args: 10); |
| 35 | std::unique_ptr<std::string> up_str = std::make_unique<std::string>(args: "hello"); |
| 36 | std::unique_ptr<int> &up_int_ref = up_int; |
| 37 | std::unique_ptr<int> &&up_int_ref_ref = std::make_unique<int>(args: 10); |
| 38 | std::unique_ptr<User> up_user = std::make_unique<User>(); |
| 39 | auto up_non_empty_deleter = |
| 40 | std::unique_ptr<int, NonEmptyIntDeleter>(new int(1234)); |
| 41 | std::unique_ptr<NodeU> ptr_node = |
| 42 | std::unique_ptr<NodeU>(new NodeU{.next: nullptr, .value: 2}); |
| 43 | ptr_node = std::unique_ptr<NodeU>(new NodeU{.next: std::move(ptr_node), .value: 1}); |
| 44 | |
| 45 | std::puts(s: "// break here"); |
| 46 | |
| 47 | recursive(); |
| 48 | |
| 49 | return 0; |
| 50 | } |
| 51 |
