Weird behavior: array of RefCounted struct
    Xaqq via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Sep  9 09:13:24 PDT 2014
    
    
  
Hello,
I'm very new to D. I started playing around trying to understand 
language behavior. How to use RAII in D, etc.
I'm having trouble understanding what is happening here, and 
maybe this is a bug.
Here is the code showing the weird behavior. I'm using dmd 2.066 
(on linux)
import std.stdio;
import std.typecons;
import std.traits;
struct Frame
{
   ~this(){
     printf("DTOR FRAME\n");
   }
   this(int v)  {
     writeln("CTOR FRAME");
     this.i = v;
   }
   int i;
}
class Container
{
   void add(int i){
     f ~= RefCounted!(Frame)(i);
   }
   ~this()  {
     printf("DTOR CONT\n");
     foreach (ref mbr; f) writeln("Count: ", 
mbr.refCountedStore.refCount);
     f = [];
   }
   this() {
     writeln("CTOR CONT");
   }
   RefCounted!(Frame)[] f;
}
void main()
{
   auto l = scoped!Container();
   foreach (i ; 1..10)
       l.add(i);
}
While the destructor of Container is called, the frame's 
destructor are not called. Printing the current reference count 
for each frame gives unexpected results.
Below is the program output:
CTOR CONT
CTOR FRAME
CTOR FRAME
CTOR FRAME
CTOR FRAME
CTOR FRAME
CTOR FRAME
CTOR FRAME
CTOR FRAME
CTOR FRAME
DTOR CONT
Count: 4
Count: 3
Count: 3
Count: 2
Count: 2
Count: 2
Count: 2
Count: 1
Count: 1
Am I doing something wrong or is this a bug? Could someone please 
try to explain?
Thanks !
    
    
More information about the Digitalmars-d-learn
mailing list