Why are structs and classes so different?

H. S. Teoh hsteoh at quickfur.ath.cx
Sun May 15 23:10:22 UTC 2022


On Sun, May 15, 2022 at 08:05:05PM +0000, Kevin Bailey via Digitalmars-d-learn wrote:
[...]
> But I asked a different question: Why can't I put a class object on
> the stack? What's the danger?
[...]

You can. Use core.lifetime.emplace.

Though even there, there's the theoretical problem of stack corruption:
if you have an emplaced class object O and you try to assign a derived
class object to it, you could end up trashing your stack (the derived
object doesn't fit in the stack space allocated to store only a base
class instance).  Generally, though, the language would prevent this.
In D this doesn't happen because emplace just gives you the class
instance as a reference (to a stack location, but nonetheless), and
reassignment just updates the reference, it doesn't actually overwrite
the base class instance.


T

-- 
If it tastes good, it's probably bad for you.


More information about the Digitalmars-d-learn mailing list