Classes on stack
IGotD-
nise at nise.com
Thu Sep 1 09:41:48 UTC 2022
On Thursday, 1 September 2022 at 09:13:56 UTC, Redwan wrote:
> Hi all
> I'm new to D from c, cpp and Rust.
>
> this language made me surprised because of its features and
> syntax and etc.
>
> but I shocked when I found that classes must be created only on
> stack! Is this nightmare real? why???
> I want declare classes and create instance of them on stack and
> nicely use them. why I must put them on heap??
> structs does not support inheritance and I don't want to use
> them. please tell me that is not true or give me some other
> ways. I don't want define objects always on heap. don't let me
> go back on cpp :( tnx!
This comes from the 90s old classes are reference type and
structs are value types (which D shares with C#). I think this
have been discussed previously in this forum and I have seen kind
of vague answer about it. However, you can allocate a class on
the stack using the scoped template. One more serious flaw to
this is that classes are not expanded as members in the host
class, which means that memory allocation and fragmentation is
much worse than people think. It is possible to expand member
classes into host classes using some kind of hack though.
For "multiple" inheritance, use composition with mixins which I
assume you are after.
Basically, I don't buy why why classes must be reference types
and must be allocated on the heap. I have not seen a good
explanation to this, or I have not fully understood it.
More information about the Digitalmars-d
mailing list