Prevent default-initialised struct
Christopher Wright
dhasenan at gmail.com
Wed Jan 28 15:45:03 PST 2009
Daniel Keep wrote:
> Hi all,
>
> is there any way to prevent a struct from being created directly?
> Basically, I want to prevent this:
>
> {
> non_null!(T) a;
> }
>
> I want people to have to use provided functions to create a structure:
>
> {
> auto a = non_null!(T)(new T);
> }
>
> -- Daniel
struct non_null(T : class)
{
// this should be private, but no can do
// an alternative is to obscure _member somehow,
// say, as a void*, just to make sure that nobody
// uses it without it being obvious that they're doing
// something bad
T _member;
T opDot ()
{
if (_member is null) _member = new T;
return T;
}
non_null!(T) opAssign(T value)
{
demand (value !is null);
_member = value;
}
}
More information about the Digitalmars-d-learn
mailing list