Allocating and freeing memory like this?
Stanislav Blinov
stanislav.blinov at gmail.com
Wed Feb 26 01:38:15 PST 2014
On Wednesday, 26 February 2014 at 09:14:42 UTC, Bienlein wrote:
A similar approach is already employed in phobos, see
http://dlang.org/phobos/std_typecons.html#.scoped
> The article confused me. Is the contents outdated or am I
> messing something up?
Regarding keywords new and delete:
http://dlang.org/class.html#allocators. Read the Notes carefully
:) In a nutshell, 'delete' keyword will eventually go away
entirely, and it won't be allowed to redefine 'new'.
Regarding the code in the article:
import std.stdio, std.conv, core.stdc.stdlib;
T _new(T, Args...) (Args args) {
size_t objSize = __traits(classInstanceSize, T);
void* tmp = core.stdc.stdlib.malloc(objSize);
if (!tmp) throw new Exception("Memory allocation failed");
Calling 'new Exception' when memory allocation failed is a bad
idea. There is std.exception.onOutOfMemoryError() function for
such cases.
void _delete(T)(T obj) {
clear(obj);
destroy(obj) should be used instead.
It's possible that some new idioms will come up once
std.allocator arrives into Phobos.
More information about the Digitalmars-d-learn
mailing list