D newb

JAnderson ask at me.com
Mon Aug 18 19:47:20 PDT 2008


bearophile wrote:
> Joel Anderson:
>>> bearophile:
>>>> My question: does the compiler raise a compilation error if the 'scope' 
>>>> keyword is used where the compiler can't actually allocate the class on 
>>>> the stack? (if not, then I think it may be better for the compiler to 
>>>> raise such error, avoiding the illusion of efficiency).
>> If the class has a component sub-class the component may be heap 
>> allocated.  I don't agree with making that an error though.
> 
> May I ask you why you don't like that as an error?
> Generally I don't like undefined situations, if I add the 'scope' keyword I want the class to be stack-allocated, and I assume the compiler does that. Then the layout of the memory used by the code is different, and I can for example take care to avoid a stack overflow. If the compiler at compile time is able to tell me that the class can't be allocated on the stack, then I think the program has to not compile until I remove the 'scope' keyword there. This makes the code reflect what the program actually does.
> 
> Bye,
> bearophile

What I'm talking about is:

class A
{


}

class B
{
...
	A a = new A(); // Heap Allocated
...
};


...

scope B b = new B; //B is scope allocated but A is not

Say your using someone else's class.  You get latest and you using one 
of there classes with the word scope.  They've decided to add something 
that is heap allocated.  Now suddenly your code is not working because 
someone made a slight change to their interface.

Of course you might not be responsible for either pieces of code.  You 
might be using a template from lib A to iterate over some class in lib 
B.  Anyway what ends up happening is the code becomes very un-generic. 
People have to create 2 versions of everything.

I think the idea of having scope members is a good one.  However if your 
using someone else class that has heap allocation you really have no 
choice.  If you make this an error then your limiting that classes use.

As to the class overflowing the stack size.  I think if a class is so 
big that that the compiler automatically heap allocates it, then there's 
a lot of other issues with your code or your running on some platform 
where it works better that way.  The compiler should do what it can to 
make sure your code runs, slow as it may be, without logical errors.

I think you always want to tell the compiler what you want to do rather 
then how and let it decide the best approach.  That way you get more 
portable code that is optimized for whatever system its going on.

-Joel



More information about the Digitalmars-d mailing list