move object from heap to stack
Johannes Pfau
nospam at example.com
Thu Sep 20 03:13:59 PDT 2012
Am Thu, 20 Sep 2012 10:11:37 +0200
schrieb "Namespace" <rswhite4 at googlemail.com>:
> You're right.
> This is my next try: http://dpaste.dzfl.pl/02b32d33
> Do you have anything else to say? :)
I think it shouldn't be possible to copy an OnStack struct. The
destructor is run for every copy, but the constructor was run only
once. So if a class keeps external references (e.g. file handles) and
closes those handles in the destructor, making a copy would result
in the destructor running twice and therefore closing the same handle
twice.
I think the usage of a OnStack struct must be quite limited to be safe:
{
auto a = OnStack!(A)(); //allocate in scope
a.doSomething(); //Calling members is fine
//a.get and a must not escape this scope (I guess we can't guarantee
//that without compiler help?)
//passing a.get to a function is valid, as long as the function
//doesn't keep a reference (the function parameter must be marked
//with scope)
someMethod(a.get);
//As a shouldn't be copied, an OnStack can't be passed to another
//function.
//no copies for OnStack allowed
//destroy at end of scope
}
Those rules are pretty strict, but maybe that's the only way to have a
safe OnStack. Maybe I forgot some detail and those rules aren't even
strict enough.
More information about the Digitalmars-d-learn
mailing list