Domanda

I've recently started learning D version 1, using the Tango library. I decided to write a small class Dout that wraps tango.io.Stdout, except it overrides opShl to better match C++'s << style output. My implementation is like so:

// dout.d
module do.Dout;

import tango.io.Stdout;

class Dout
{
    public static Dout opShl(T) (T arg)
    {
        stdout(arg);
        return new Dout;
    }

    public static Dout newline()
    {
        stdout.newline;
        return new Dout;
    }
}

And in main, I make a simple call to Dout.opShl(), like so.

// main.d
import do.Dout;
import tango.io.Console;

int main(char[][] argv)
{
    Dout << "Hello" << " world!" << Dout.newline;
    Cin.get();
    return 0;
}

This works, but after pressing enter and exiting main, the text "do.Dout.Dout" is printed. After stepping through the code, I found that this text is printed at the assembly instruction:

00406B5C call __moduleDtor (40626Ch)

In which do.Dout's destructor is being called.

My question is, why is the module name being printed upon exiting main, and what can I do to stop this behaviour?

È stato utile?

Soluzione

the reason "do.Dout.Dout" is printed is because Dout << Dout.newline; prints a new line (in the newline property call) and then attempts to print a human readable string of a Dout object (after it is passed to opShl!Dout())

and you only see it during destruction because then the output is flushed ;)

you should have done

__gshared Doutclass Dout = new Doutclass;

class Doutclass
{
    public Dout opShl(T) (T arg)
    {
        static if(T == NLine){
            stdout.newline;//if nl is passed do newline
        }else{
            stdout(arg);
        }
        return this;
    }

    struct NLine{}//this might need a dummy field to stop compiler complaints
    public static NLine newline()
    {
        return NLine();
    }
}

which is closer to the C style (Dout is an global object and doesn't get recreated each call, newline is a special struct that flushed the output besides adding a newline to it)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top