www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Should this be a compiler error?

reply Mike L. <mike.linford gmail.com> writes:
The following code compiles fine for me with dmd 1.043:

----------
module wtf;

version(Tango)
	import tango.io.Stdout;
else
	import std.stdio;

interface Printer
{
	void print();
}

class WTF
{
	Printer p;
	
	this(int x)
	{
		p = new class Printer
		{
			override void print()
			{
				version(Tango)
					Stdout(x).newline();
				else
					writefln(x);
			}
		};
	}
}

void main()
{
	WTF wtf = new WTF(42);
	wtf.p.print();
}
----------

The anonymous class is given a method that prints the int x, however, by the
time wtf.p.print() is called, x has gone out of scope. It's still possible to
call the print(), though, and it just prints garbage. Should this be a compiler
error?
Jun 07 2009
next sibling parent reply Jason House <jason.james.house gmail.com> writes:
Mike L. Wrote:

 The following code compiles fine for me with dmd 1.043:
At least for closures, D2 will catch this type of issue. I doubt such escaping stack frame issues will get addressed in D1. Either way, you should submit a bugzilla entry.
 
 ----------
 module wtf;
 
 version(Tango)
 	import tango.io.Stdout;
 else
 	import std.stdio;
 
 interface Printer
 {
 	void print();
 }
 
 class WTF
 {
 	Printer p;
 	
 	this(int x)
 	{
 		p = new class Printer
 		{
 			override void print()
 			{
 				version(Tango)
 					Stdout(x).newline();
 				else
 					writefln(x);
 			}
 		};
 	}
 }
 
 void main()
 {
 	WTF wtf = new WTF(42);
 	wtf.p.print();
 }
 ----------
 
 The anonymous class is given a method that prints the int x, however, by the
time wtf.p.print() is called, x has gone out of scope. It's still possible to
call the print(), though, and it just prints garbage. Should this be a compiler
error?
Jun 08 2009
parent grauzone <none example.net> writes:
 Either way, you should submit a bugzilla entry.
Why should he file a bug report for something that's not a bug?
Jun 08 2009
prev sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
Mike L. Wrote:

 The following code compiles fine for me with dmd 1.043:
[snip]
 Should this be a compiler error?
No, because what you are asking for requires full escape analysis (that is, determining if a variable escapes its scope). In order to do that, dmd needs full sources or an intermediate format for compilation, and not to mention a major redesign of the compiler. These sorts of things have been asked for in the past, to no avail. Either the solutions require major annotation by a person, or major redesign of the language. D2 handles this by allocating a closure. D1 is in feature freeze so it won't get any enhancements. Both solutions (silently allocate heap data "just in case", or just close your eyes and still compile) kinda suck. The best I can say is, you should learn to avoid these types of things. -Steve
Jun 08 2009