refCounted

Initializes a RefCounted with val. The template parameter T of RefCounted is inferred from val. This function can be used to move non-copyable values to the heap. It also disables the autoInit option of RefCounted.

Parameters

val T

The value to be reference counted

Return Value

Type: RefCounted!(T, RefCountedAutoInitialize.no)

An initialized RefCounted containing val.

Examples

1 static struct File
2 {
3     string name;
4     @disable this(this); // not copyable
5     ~this() { name = null; }
6 }
7 
8 auto file = File("name");
9 assert(file.name == "name");
10 // file cannot be copied and has unique ownership
11 static assert(!__traits(compiles, {auto file2 = file;}));
12 
13 // make the file refcounted to share ownership
14 import std.algorithm.mutation : move;
15 auto rcFile = refCounted(move(file));
16 assert(rcFile.name == "name");
17 assert(file.name == null);
18 auto rcFile2 = rcFile;
19 assert(rcFile.refCountedStore.refCount == 2);
20 // file gets properly closed when last reference is dropped

See Also

Meta

Suggestion Box / Bug Report