www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Prevent default-initialised struct

reply Daniel Keep <daniel.keep.lists gmail.com> writes:
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
Jan 26 2009
next sibling parent reply BCS <none anon.com> writes:
Hello Daniel,

 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 S { private static S opCall(); } //???
Jan 26 2009
parent "Denis Koroskin" <2korden gmail.com> writes:
On Mon, 26 Jan 2009 20:40:01 +0300, BCS <none anon.com> wrote:

 Hello Daniel,

 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 S { private static S opCall(); } //???
Nope: S s; //okay
Jan 26 2009
prev sibling next sibling parent reply grauzone <none example.net> writes:
I think it would really suck to introduce special cases to forbid 
default initialization of structs. And assuming T was the type of the 
struct, what would T.init do? Or typeid(T).init()?

Use a class instead.

If you really need a struct, you could use a private field, that signals 
if the struct was properly initialized.

E.g.

struct Foo {
	debug private bool initialized;
	
	static Foo opCall() {
		Foo n;
		debug n.initialized = true;
		return n;
	}
	
	void foo() {
		assert (initialized);
		//do something useful
	}
}
Jan 28 2009
parent Daniel Keep <daniel.keep.lists gmail.com> writes:
grauzone wrote:
 Use a class instead.
That would defeat the purpose of defining a non_null template in the first place. -- Daniel
Jan 28 2009
prev sibling parent Christopher Wright <dhasenan gmail.com> writes:
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; } }
Jan 28 2009