Delay allocating class instance in stack.

Stefan Koch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 21 05:30:57 PDT 2017


On Tuesday, 21 March 2017 at 08:08:24 UTC, ANtlord wrote:
> Hello! I read documentation about memory management and can't 
> find description about delay allocation of instance. I have a 
> method marked by @nogc. This method takes boolean variable. If 
> this variable is true I want to construct object with one set 
> of parameters else I want to construct object with another set 
> of parameters. Take a look at code for clearance.
>
> void method(bool flag) @nogc
> {
> 	scope MyClass obj;
> 	if(flag) {
> 		obj = new MyClass(1);
> 	} else {
> 		obj = new MyClass(2);
> 	}
> 	// using obj
> }
>
> But this code CAN'T be compiled. How should I declare object 
> for delay construction.
> Thanks.

Try scope obj = new MyClass(flag ? 1 : 2);

In essence you should never need to delay construction.
Just construct the object as soon as you have everything to 
construct it.
which includes conditions.


More information about the Digitalmars-d-learn mailing list