"Value class instance" pattern?
bearophile
bearophileHUGS at lycos.com
Sun Jul 14 05:25:51 PDT 2013
Benjamin Thaut:
>> Trying to use ClassCompose in my code I have had some problems
>> caused by const classes and ClassCompose dtor. Maybe such dtor
>> (and isDestructed) can be versioned out for composed-in classes
>> that only contain values...
>
> Can you give an example for that?
As a simple example try to make this work:
struct UseDefaultCtor {}
/// Call default ctor type for Composition.
enum useDefaultCtor = UseDefaultCtor();
struct Composition(T) if (is(T == class)) {
void[__traits(classInstanceSize, T)] classInstanceBuf = void;
bool isDestructed = false;
@property T _instance() {
return cast(T)classInstanceBuf.ptr;
}
@property const(T) _instance() const {
return cast(const T)classInstanceBuf.ptr;
}
alias _instance this;
@disable this();
@disable this(this);
this()(UseDefaultCtor) {
classInstanceBuf[] = typeid(T).init[];
_instance.__ctor;
}
this(Targs...)(Targs args)
if (__traits(compiles, _instance.__ctor(args))) {
classInstanceBuf[] = typeid(T).init[];
_instance.__ctor(args);
}
~this() {
if (!isDestructed) {
_instance.destroy;
isDestructed = true;
}
}
}
// ----------------------------------
const class Foo {
int x;
this(int xx) const pure nothrow {
this.x = x;
}
}
const class Bar {
const Composition!Foo f;
this(int x) const pure nothrow {
f = typeof(f)(x);
}
}
void main() {}
>> Maybe such alignment can be added to the ClassCompose too.
>>
>
> But that would be a uneccessary overhead. Just adding a
> align(4) or align(16) like suggested below would be sufficient.
I don't understand. What overhead? It's an annotation that
depends on the contents of ClassCompose. I think it should cause
no bad overhead.
Bye,
bearophile
More information about the Digitalmars-d
mailing list