Understanding Safety of Function Pointers vs. Addresses of Functions

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 7 13:13:07 PDT 2015


On Tuesday, 7 July 2015 at 19:54:19 UTC, jmh530 wrote:
> I'm not sure I understand the safety of function pointers vs. 
> the addresses of functions. The code below illustrates the 
> issue.
>
> I was under the impression that pointers are not allowed in 
> safe code.

No, pointers are fine. It's pointer arithmetic that's considered 
unsafe.

> Naturally, I took that to also mean that function pointers are 
> not allowed in safe code. Indeed, I haven't been able to pass a 
> function pointer to a safe function. However, I am able to take 
> the address of a function and pass that as a parameter. It 
> seems to work fine for taking the address of functions and 
> templates (so long as I !)

So long as you exclamation mark? Huh?

> import std.stdio : writeln;
> import std.traits;
> import std.math;
>
> void function_safety(T)(T fp)
> {
> 	if (functionAttributes!fp & FunctionAttribute.safe)
> 		writeln("fp is safe");
> 	else if (functionAttributes!fp & FunctionAttribute.trusted)
> 		writeln("fp is trusted");
> 	else if (functionAttributes!fp & FunctionAttribute.system)
> 		writeln("fp is system");
> 	else
> 		writeln("fp is neither safe nor trusted nor system");
> }
>
> void main()
> {
> 	function_safety(&cbrt);  //prints fp is trusted
> 	real function(real) fp = &cbrt;

You're explicitly typing that as `real function(real)` which is 
not an @safe type. Add @safe and you're good to go:

real function(real) @safe fp = &cbrt;
function_safety(fp); /* prints "fp is safe" */

Or let the compiler infer things:

auto fp = &cbrt;
function_safety(fp); /* prints "fp is trusted" */

> 	function_safety(fp);     //prints fp is system
> }


More information about the Digitalmars-d-learn mailing list