|
1 | | -# observable_unique_ptr |
2 | | -A unique-ownership smart pointer that can be observed with weak pointers |
| 1 | +# observable_unique_ptr<T, Deleter> |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +This is a small header-only library, providing a unique-ownership smart pointer that can be observed with weak pointers. It is a mixture of `std::unique_ptr` and `std::shared_ptr`: it borrows the unique-ownership semantic of `std::unique_ptr` (movable, non-copiable), but allows creating `std::weak_ptr` instances to monitor the lifetime of the pointed object. |
| 6 | + |
| 7 | +This is useful for cases where the shared-ownership of `std::shared_ptr` is not desirable, e.g., when lifetime must be carefully controlled and not be allowed to extend, yet non-owning "weak" references to the object may exist after the object has been deleted. |
| 8 | + |
| 9 | + |
| 10 | +## Usage |
| 11 | + |
| 12 | +This is a header-only library. You have multiple ways to set it up: |
| 13 | + - just include this repository as a submodule in your own git repository and use CMake `add_subdirectory`, |
| 14 | + - use CMake `FetchContent`, |
| 15 | + - download the header and include it in your own sources. |
| 16 | + |
| 17 | +From there, include the single header `<oup/observable_unique_ptr.hpp>`, and directly use the smart pointer in your own code: |
| 18 | + |
| 19 | +```c++ |
| 20 | +#include <oup/observable_unique_ptr.hpp> |
| 21 | + |
| 22 | +int main() { |
| 23 | + // Weak pointer that will outlive the object |
| 24 | + oup::weak_ptr<std::string> wptr; |
| 25 | + |
| 26 | + { |
| 27 | + // Unique pointer that owns the object |
| 28 | + auto ptr = oup::make_observable_unique<std::string>("hello"); |
| 29 | + |
| 30 | + // Make the weak pointer observe the object |
| 31 | + wptr = ptr; |
| 32 | + |
| 33 | + // Weak pointer is valid |
| 34 | + assert(!wptr.expired()); |
| 35 | + |
| 36 | + // It can be locked to get a (non-owning!) pointer to the object |
| 37 | + std::string* s = wptr.lock(); |
| 38 | + assert(s != nullptr); |
| 39 | + std::cout << *s << std::endl; |
| 40 | + |
| 41 | + // The unique pointer cannot be copied |
| 42 | + oup::observable_unique_ptr<std::string> tmp_copied = ptr; // error! |
| 43 | + |
| 44 | + // ... but it can be moved |
| 45 | + oup::observable_unique_ptr<std::string> tmp_moved = std::move(ptr); // OK |
| 46 | + } |
| 47 | + |
| 48 | + // The unique pointer has gone out of scope, the object is deleted, |
| 49 | + // the weak pointer is now null. |
| 50 | + assert(wptr.expired()); |
| 51 | + assert(wptr.lock() == nullptr); |
| 52 | + |
| 53 | + return 0; |
| 54 | +} |
| 55 | +``` |
0 commit comments