I can has @nogc and throw Exceptions?
Tobias Pankrath via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 13 11:09:42 PST 2015
On Friday, 13 February 2015 at 19:03:10 UTC, Jonathan Marler
wrote:
> This question comes from wanting to be able to throw an
> exception in code that is @nogc.
>
> I don't know if it's possible but I'd like to be able to throw
> an exception without allocating memory for the garbage
> collector? You can do it in C++ so I think you should be able
> to in D. One idea I had was to allocate the memory for the
> Exception beforehand and create the Exception class with the
> pre-allocated memory. I came up with the following code:
>
> T construct(T,A...)(void* buffer, A args)
> {
> return (cast(T)buffer).__ctor(args);
> }
>
> Now to test it:
>
> void main()
> {
> ubyte[ __traits(classInstanceSize, Exception)]
> exceptionBuffer;
> throw construct!(Exception)(exceptionBuffer.ptr, "My
> Exception Allocated on the STACK!");
> }
>
> I got an assertion error. I'm not sure why, but when I print
> out the contents of the buffer of my stack exception it differs
> from an exception created for the garbage collector with "new".
> It looks like it has some accounting information embedded in
> the class instance. I figured as much but I didn't think the
> code that performs the "throw" would be dependent on this.
>
> Also, this doesn't look like a very safe option because the
> initial values for the class members don't get set using this
> "construct" template.
>
> If anyone has any other ideas or a way to fix mine let me know,
> thanks.
1. Throw preallocated exceptions is the way to go
2. Allocating them on the stackframe that will cease to exist by
throwing is a bad idea
3. use emplace
To construct a type in preallocated memory
More information about the Digitalmars-d-learn
mailing list