fork download
  1.  
  2. import std.stdio;
  3.  
  4. struct A
  5. {
  6.  
  7. void set(ref B b)
  8. {
  9. myB = &b;
  10. }
  11.  
  12. void set(B)
  13. {
  14. writeln("Nope.");
  15. }
  16.  
  17. void voiceOfB()
  18. {
  19. myB.voice();
  20. }
  21.  
  22. private:
  23.  
  24. const(B)* myB;
  25.  
  26. }
  27.  
  28. struct B
  29. {
  30. this(int v)
  31. {
  32. value = v;
  33. }
  34.  
  35. ~this()
  36. {
  37. value = -1;
  38. }
  39.  
  40. void voice() const
  41. {
  42. writeln("I am B with value = ", value);
  43. }
  44.  
  45. ref A setSelfForA(ref A a)
  46. {
  47. a.set(this);
  48. return a;
  49. }
  50.  
  51. int value = 0;
  52. }
  53.  
  54. int main(string[] argv)
  55. {
  56. A a;
  57.  
  58. a.set(B()); // no way to pass this value without copying
  59. // my guess is to try and keep it safe
  60. // but then you get the below case which is possible
  61. // maybe it's just an overlooked detail but it is possible currently..
  62.  
  63. B(42).setSelfForA(a)
  64. .voiceOfB();
  65.  
  66. a.voiceOfB();
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0s 2688KB
stdin
Standard input is empty
stdout
Nope.
I am B with value = 42
I am B with value = -1