rcClass

Constructs a new reference-counted instance of C. (An external factory function is used instead of static opCall to avoid conflicting with the class's non-static opCall.)

template rcClass(C)
rcClass
(
Args...
)
(
auto ref Args args
)
if (
is(C == class) &&
is(typeof(emplace!C(null, args)))
)
if (
is(C == class)
)

Members

Functions

rcClass
RCClass!C rcClass(Args args)
Undocumented in source. Be warned that the author may not have intended to support it.

Examples

Constructors

void ctorTest(bool haveArglessCtor, bool haveArgCtor)()
{
	static class C
	{
		int n = -1;

		static if (haveArglessCtor)
			this() { n = 1; }

		static if (haveArgCtor)
			this(int val) { n = val; }

		~this() { n = -2; }
	}

	RCClass!C rc;
	assert(!rc);

	static if (haveArglessCtor || !haveArgCtor)
	{
		rc = rcClass!C();
		assert(rc);
		static if (haveArglessCtor)
			assert(rc.n == 1);
		else
			assert(rc.n == -1); // default value
	}
	else
		static assert(!is(typeof(rcClass!C())));

	static if (haveArgCtor)
	{
		rc = rcClass!C(42);
		assert(rc);
		assert(rc.n == 42);
	}
	else
		static assert(!is(typeof(rcClass!C(1))));

	rc = null;
	assert(!rc);
}

import std.meta : AliasSeq;
foreach (haveArglessCtor; AliasSeq!(false, true))
	foreach (haveArgCtor; AliasSeq!(false, true))
		ctorTest!(haveArglessCtor, haveArgCtor);

Lifetime

static class C
{
	static int counter;

	this() { counter++; }
	~this() { counter--; }
}

{
	auto a = rcClass!C();
	assert(C.counter == 1);
	auto b = a;
	assert(C.counter == 1);
}
assert(C.counter == 0);

Inheritance

static class Base
{
	int foo() { return 1; }
}

static class Derived : Base
{
	override int foo() { return 2; }
}

auto derived = rcClass!Derived();
RCClass!Base base = derived; // initialization
base = derived;              // assignment
static assert(!is(typeof(derived = base)));
auto base2 = cast(RCClass!Base)derived;

Non-static opCall

static class C
{
	int calls;
	void opCall() { calls++; }
}

auto c = rcClass!C();
assert(c.calls == 0);
c();
assert(c.calls == 1);

Casting

static class A {}
static class B : A {}
static class C : A {}
RCClass!A a = rcClass!B();
assert( cast(RCClass!B)a);
assert(!cast(RCClass!C)a);

Meta