1 /** 2 Weak pointers 3 4 Copyright: 5 Copyright © 2023-2025, Kitsunebi Games 6 Copyright © 2023-2025, Inochi2D Project 7 8 License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) 9 Authors: Luna Nielsen 10 */ 11 module nulib.memory.weak_ptr; 12 import nulib.memory.internal; 13 import numem.core.traits; 14 import numem; 15 16 /** 17 A weak pointer. 18 19 Weak pointers point to memory owned by shared_ptr or unique_ptr. 20 They do not own the memory allocation and said allocation may 21 become $(D null) at any point. 22 23 Make sure to check the validity of the underlying value using 24 $(D isValid)! 25 26 See_Also: 27 $(D nulib.memory.shared_ptr.shared_ptr) 28 $(D nulib.memory.unique_ptr.unique_ptr) 29 */ 30 struct weak_ptr(T) { 31 @nogc: 32 private: 33 __refcount_t!(T)* ptr = null; 34 35 package(nulib.memory): 36 37 /** 38 Constructs a weak pointer from an internal refcount object. 39 */ 40 this(__refcount_t!T* ptr) @system { 41 this.ptr = ptr; 42 ptr.retain!false; 43 } 44 45 public: 46 alias value this; 47 48 /** 49 The value stored within the smart pointer. 50 */ 51 @property ref T value() @trusted nothrow { 52 return ptr.get(); 53 } 54 55 /** 56 Whether the smart pointer value is still valid. 57 */ 58 @property bool isValid() @trusted nothrow { 59 return ptr && ptr.strongrefs > 0 && ptr.ptr !is null; 60 } 61 62 /// Destructor. 63 ~this() @trusted { 64 if (ptr) { 65 ptr.release!false; 66 ptr = null; 67 } 68 } 69 70 /** 71 Copy Constructor. 72 */ 73 this(ref inout(typeof(this)) src) { 74 auto srcobj = cast(Unqual!(typeof(this)))src; 75 76 this.ptr = srcobj.ptr; 77 this.ptr.retain!false; 78 } 79 }