@safe quiz

Michel Fortin michel.fortin at michelf.com
Wed Dec 30 04:38:13 PST 2009


I've encountered the two following situations when playing with @safe 
and delegate literals, and I had to label more code as @trusted than I 
expected.

Here is some code:

	@safe void test(void function(int) doX, int i) {
		doX(i);
	}

	void main() {
		test((int i) { writeln(i); }, 1);
	}

Note that doSomething and main are not safe. Should that compile? 
Currently it doesn't with an error on the "doX(i);" line saying doX 
isn't @safe. (The compiler won't let you label the argument @safe 
either.) I think it should compile because it's main that should be 
held responsible for the code it gives to test, and since main isn't a 
safe function it should be allowed to pass something unsafe, even to a 
safe function.

Now let's do the same using a template:

	@safe void test(alias doX)(int i) {
		doX(i);
	}

	void main() {
		test!((int i) { writeln(i); })(1);
	}

Same here, except that instead of a function pointer we have a 
template. Should that compile? Basically, it's the same situation as 
above, and it doesn't compile either.

Which makes me think that obviously the same thing will happen with 
string mixins:

	@safe void test(string doX)(int i) {
		mixin(doX~";");
	}

	void main() {
		test!("writeln(i)")(1);
	}

Here, if writeln wasn't safe (and it currently isn't, that should be 
fixed in Phobos) there is no way this can compile. This is going to be 
pretty annoying if std.algorithm ever become @safe.

I'm not sure what should happen in the template case.


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list