Do functions and/or function pointers have scope (or lifetimes)

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 29 15:06:24 PST 2014


On Sat, Nov 29, 2014 at 10:59:21PM +0000, WhatMeWorry via Digitalmars-d-learn wrote:
> 
> I'm assuming the answer is yes.
> 
> If so, that implies that I could execute a function pointer that
> doesn't point to anything meaningful. Conversely, functionality could
> exist that I can't get access to because my function pointer is
> unavailable?
> 
> If these are dangers, is there a technique or mechanism that I can use
> to always ensure that both these scenarios never happen.
> 
> Andrei's book mentions that reference types live forever (or something
> to that effect) as opposed to value types. So could I put functions
> and function pointers into Class objects?
[...]

Functions always exist throughout the lifetime of your program -- they
*are* a part of your executable after all -- so function pointers are
always valid. (Well, unless you got them from a manually-loaded dynamic
library that gets subsequently unloaded, but I'm assuming that if you're
doing *that*, then you already know the answers to your question.)

Delegates also live forever, even though technically the GC could
collect the context part of the delegate once there are no more
references to it. But since delegates are built into the language, and
the GC will never collect their contexts as long as you have references
to them, you don't have to worry about it either. (Of course, delegates
come with other gotchas -- for example, they can close over a reference
to a variable that subsequently goes out of scope, but in theory the
compiler should warn you about that, or automatically allocate said
variable on the heap instead of the stack, so you should still be OK in
that case. There *are* some cases where you have to be careful, such as
closing over the address of a struct member, because structs are
movable, so by the time the delegate runs, the reference may already be
invalid. But this is quite rare to run into.)

tl;dr, yes you can put function pointers into class objects without
getting yourself into trouble.


T

-- 
Let X be the set not defined by this sentence...


More information about the Digitalmars-d-learn mailing list