structs vs classes
Simen kjaeraas
simen.kjaras at gmail.com
Sat Jan 29 08:04:48 PST 2011
Jim <bitcirkel at yahoo.com> wrote:
> "All class-based objects are dynamically allocated—unlike in C++, there
> is no way to allocate a class object on the stack."
> - The D Programming Language, chapter 6.
That would probably be better written as "there is no built-in way to
allocate a class object on the stack." D is a pragmatic system programming
language. If you want to treat this blob of memory as a Foo, and you're
willing to jump through some hoops, it can be done. But the language does
not encourage this.
Like I said, putting a class on the stack is an unsafe thing to do (see
http://en.wikipedia.org/wiki/Object_slicing), and it was deemed that the
language should not directly support such an idiom. It is still doable in
a library.
> The lightweight nature of structs is very appealing though. I like that
> very much of course. Couldn't that be optimised by the compiler alone
> knowing that a class wasn't derived?
Perhaps, in some cases. Final classes might. If a class is not marked
final, someone might derive from it, include this from a DLL or otherwise,
and boom goes the program.
--
Simen
More information about the Digitalmars-d
mailing list