struct vs class for a simple token in my d lexer
Jonathan M Davis
jmdavisProg at gmx.com
Mon May 14 09:41:23 PDT 2012
On Monday, May 14, 2012 17:10:23 Roman D. Boiko wrote:
> (Subj.) I'm in doubt which to choose for my case, but this is a
> generic question.
>
> http://forum.dlang.org/post/odcrgqxoldrktdtarskf@forum.dlang.org
>
> Cross-posting here. I would appreciate any feedback. (Whether to
> reply in this or that thread is up to you.) Thanks
For the question in general, there are primarily 2 questions to consider:
1. Do you need inheritance/polymorphism?
2. Do you need a value type or a reference type?
If you need inheritance/polymorphism, you have to use classes, because structs
don't have inheritance.
If you want a value type, you have to use structs, because classes are
reference types.
If you want a reference type, then you can use either a class or a struct, but
it's easier with classes, because classes are always reference types, whereas
structs are naturally value types, so it can take more work to make them
reference types depending on what its member variables are.
One other thing to consider is deterministic destruction. The only way to get
deterministic destruction is to have a struct on the stack. Value types will
naturally get that, but if you want a reference type with determinstic
destruction, then you're probably going to have to use a ref-counted struct.
In the vast majority of cases, that should be enough to decide whether you
need a class or a struct. The main case that it doesn't is the case where you
want a reference type and don't necessarily want a class, and that decision
can get complicated.
In the case of a token in a lexer, I would definitely expect that to be a value
type, which means using a struct.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list