Virtual methods on stack objects

Ali Çehreli acehreli at yahoo.com
Wed May 11 20:23:07 UTC 2022


On 5/11/22 13:06, Marvin Hannott wrote:

 > I appreciate the answer, don't much like the "solutions".

Me neither. :)

 > It's not so much about copying

Great!

 > scoped class objects should have value semantics.

std.typecons.scoped does exactly that:

   https://dlang.org/phobos/std_typecons.html#scoped

import std.stdio;
import std.typecons;

interface Animal {
   string sing();
}

class Cat : Animal {
   this() {
     writeln("Hi!");
   }

   ~this() {
     writeln("Bye!");
   }

   string sing() {
     return "mew";
   }
}

void foo(Animal animal) {
   writeln(animal.sing());
}

void bar() {
   auto cat = scoped!Cat();
   foo(cat);
}

void main() {
   bar();
}

The output:

Hi!
mew
Bye!

Ali



More information about the Digitalmars-d-learn mailing list