1 /** 2 C++-style automatic memory management smart pointers for D using `stdx.allocator`. 3 4 Unlike the C++ variants, the smart pointers themselves allocate the memory for the objects they contain. 5 That ensures the right allocator is used to dispose of the memory as well. 6 7 Allocators are template arguments instead of using `theAllocator` so 8 that these smart pointers can be used in `@nogc` code. However, they 9 will default to `typeof(theAllocator)` for simplicity. The examples 10 above will be explicit. 11 12 Another reason to have to pass in the type of allocator is to decide how it is to 13 be stored. Stateless allocators can be "stored" by value and imply zero-cost `Unique` pointers. 14 Singleton allocators such as Mallocator (that have an `instance` attribute/member function) 15 don't need to be passed in to the constructor. This is detected at compile-time as an example 16 of design by instrospection. 17 18 `RefCounted` leverages D's type system by doing atomic reference counting *iff* the type of the contained 19 object is `shared`. Otherwise it's non-atomic. 20 */ 21 module automem; 22 23 public import automem.unique; 24 public import automem.ref_counted; 25 public import automem.vector; 26 public import automem.array; 27 public import automem.unique_array; 28 29 30 /** 31 This unittest can be @safe if the allocator has @safe functions 32 */ 33 @system @nogc unittest { 34 35 import stdx.allocator.mallocator: Mallocator; 36 import std.algorithm: move; 37 38 struct Point { 39 int x; 40 int y; 41 } 42 43 { 44 // must pass arguments to initialise the contained object 45 auto u1 = Unique!(Point, Mallocator)(2, 3); 46 assert(*u1 == Point(2, 3)); 47 assert(u1.y == 3); 48 49 // auto u2 = u1; // won't compile, can only move 50 typeof(u1) u2 = u1.move; 51 assert(cast(bool)u1 == false); // u1 is now empty 52 } 53 // memory freed for the Point structure created in the block 54 55 { 56 auto s1 = RefCounted!(Point, Mallocator)(4, 5); 57 assert(*s1 == Point(4, 5)); 58 assert(s1.x == 4); 59 { 60 auto s2 = s1; // can be copied 61 } // ref count goes to 1 here 62 63 } // ref count goes to 0 here, memory released 64 65 { 66 // the constructor can also take (size, init) or (size, range) values 67 auto arr = UniqueArray!(Point, Mallocator)(3); 68 69 const Point[3] expected1 = [Point(), Point(), Point()]; // because array literals aren't @nogc 70 assert(arr[] == expected1); 71 72 const Point[1] expected2 = [Point()]; 73 arr.length = 1; 74 assert(*arr == expected2); //deferencing is the same as slicing all of it 75 76 arr ~= UniqueArray!(Point, Mallocator)(1, Point(6, 7)); 77 const Point[2] expected3 = [Point(), Point(6, 7)]; 78 assert(arr[] == expected3); 79 80 } // memory for the array released here 81 } 82 83 /// 84 @("theTestAllocator") 85 @system unittest { 86 87 with(theTestAllocator) { 88 auto ptr = Unique!int(42); 89 assert(*ptr == 42); 90 } 91 // TestAllocator will throw here if any memory leaks 92 }