Factory Method

Bill Baxter dnewsgroup at billbaxter.com
Wed Sep 19 14:22:51 PDT 2007


Klaus Friedel wrote:
> Nathan Reed Wrote:
> 
>> Klaus Friedel wrote:
>>> Im sure I missed something. I tried to create a factory class producing objects on the heap like I would in C++ or Java:
>>>
>>> //**************************************
>>> class Cat{
>>>   int id;
>>> }
>>>
>>> class CatFactory{
>>>   Cat * createCat(){
>>>     Cat aCat = new Cat();
>>>     return &aCat;
>>>   }
>>> }
>>>
>>> void test(){
>>>   CatFactory factory = new CatFactory();
>>>   Cat *c1 = factory.create();
>>>   Cat *c2 = factory.create();
>>> }
>>> //**************************************************************
>>>
>>> I discoverd this would not work because aCat will be allocated on the stack instead the heap.
>>> Why ???? Looks anything but intuitive to me.
>>> What would be the correct way to create a object on the GC controlled heap an return a reference to that object ?
>> In D, classes are reference types.  This means when you declare a 
>> variable like "Cat aCat", that is really a reference to a Cat, and is 
>> allocated on the heap, not the stack.  So, the correct way to do this 
>> would be:
>>
>> class CatFactor {
>>    Cat createCat () {
>>      return new Cat;
>>    }
>> }
>>
>> The function allocates a Cat and returns a reference to it.  Pointers 
>> are not necessary.
>>
>> Thanks,
>> Nathan Reed
> 
> Thanks for the fast reply. I was sure I missed something ;-)
> What really confused me was the following statement under "Memory Management" http://www.digitalmars.com/d/memory.html#stackclass :
> 
>>>> Class instances are normally allocated on the garbage collected heap. However, if they:
>>>>
>>>>    * are allocated as local symbols in a function
>>>>    * are allocated using new
>>>>    * use new with no arguments
>>>>    * have the scope storage class
>>>>
>>>> then they are allocated on the stack. This is more efficient than doing an allocate/free >>>cycle on the instance. But be careful that any reference to the object does not survive the return of the function.
> 
> I thought of the "*" as "or" but after rereading I now understand it ment "and".
> Maybe somebody should edit this chapter to prevent others from making the same mistake ?
> 

Yeh, that is ambiguous.
Care to file a doc bug on it?

I think inserting one 'and' is all that's needed:
"""
* are allocated as local symbols in a function
* are allocated using new
* use new with no arguments
* and have the scope storage class
"""

Bugzilla is here:
http://d.puremagic.com/issues/

--bb



More information about the Digitalmars-d mailing list