List of Phobos functions that allocate memory?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Feb 6 11:18:53 PST 2014


On Thu, Feb 06, 2014 at 11:01:18AM -0800, Andrei Alexandrescu wrote:
> On 2/6/14, 10:52 AM, fra wrote:
> >On Thursday, 6 February 2014 at 18:20:56 UTC, Andrei Alexandrescu wrote:
> >>>One interesting point is that module that were written with
> >>>avoiding allocations in mind usually still allocate when throwing
> >>>exceptions.
> >>
> >>Good point, we need to address that as well.
> >>
> >>
> >>Andrei
> >
> >Hey, wait a second. How do you throw without allocating?
> 
> I don't know yet. That's what the "addressing the problem" will take
> care of! :o)
[...]

You can just pre-declare the Exception as a global variable and then
throw that. Well, OK, it's cheating because you still have to allocate
it then, but the point is that you get to control how it gets allocated
at the top-level rather than having the 'new' buried deep down in the
function call chain where you can't control whether the code uses 'new'
or a custom allocator (it may not know about which allocator to use).

	Exception prealloc_exc;
	static this() {
		prealloc_exc = ... /* use whatever allocation method you want */
	}
	void main() {
		try {
			func();
		} catch(Exception e) {
			// you get prealloc_exc here
		}
	}
	void func() {
		if (error) {
			// init exception parameters
			prealloc_exc.msg = ...;
				/* presumably you preallocate the
				 * message string too, with the
				 * allocator of your choice */

			throw prealloc_exc; // N.B. no allocation
		}
	}


T

-- 
Doubtless it is a good thing to have an open mind, but a truly open mind should be open at both ends, like the food-pipe, with the capacity for excretion as well as absorption. -- Northrop Frye


More information about the Digitalmars-d mailing list