Scoped Class Instance
Simen Kjærås
simen.kjaras at gmail.com
Tue Jan 31 08:05:55 PST 2012
On Tue, 31 Jan 2012 16:42:52 +0100, Zachary Lund <admin at computerquip.com>
wrote:
> On Tuesday, 31 January 2012 at 15:19:00 UTC, Trass3r wrote:
>>> However, I cannot, by default, scope my custom allocations.
>>> Any ideas?
>>
>> std.typecons.scoped
>
> I looked into this and I'm unsure of its exact use. It says, "Allocates
> a class object right inside the current scope" which doesn't really
> define how it's allocated nor does it explain how this would work with
> custom de/allocators. Also, it claims it "avoids" the overhead of new of
> which I'm not entirely sure of what it means. Could some clarification
> be made?
If scoped is used inside a struct or class, it allocates the space within
that struct or class. If used inside a function, the space is allocated
on the stack. The size of the allocated buffer must be known at compile
time, so you may not put an instance of a subclass into a scoped variable.
Because the class may be allocated on the stack, returning it from a
function is a Bad Idea™, unless it's part of a struct or class you know
will survive for a while longer.
The reason it avoids the overhead of new is it does not allocate using
new. Basically, Scoped does this:
class A {}
A scoped = cast(A)alloca(sizeof(A));
A.__ctor(args);
More information about the Digitalmars-d-learn
mailing list