[Issue 1778] Can not create pointer to class reference

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Jan 17 01:15:46 PST 2008


http://d.puremagic.com/issues/show_bug.cgi?id=1778


aarti at interia.pl changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|RESOLVED                    |REOPENED
         Resolution|INVALID                     |




------- Comment #2 from aarti at interia.pl  2008-01-17 03:15 -------
Well, the problem is not that simple as it seems to be...

Currently it is NOT possible to create in sane way pointer to class reference
on heap. It affects also all types of form:
A**, A***, A**** ...., where A is a class
because to initialize them it is necessary at last to initialize A*.

Because of pointer is not created, there is no way to initialize such a
variable.

More comments in below example:
import std.stdio;

T create(T)() {
    static if (is(T == class))
        return new T;
    else
        return *(new T);
}

class A { void test() {writefln("Ok!");}}
struct B {}

void main() {
    //Does not create pointer to A in memory
    A* x = *(new A*);
    writefln("x is null: ", x is null);
    //*x = new A; //access violation, because x is null as only 
                  //first pointer is created

    //How to initialize below variable?
    A** y = new A*;
    //*y = ????


    //Workaroud 1
    A* u = cast(A*) new B;
    *u = new A;
    u.test;

    //Workaround 2
    static A ca;
    ca = new A;
    u = &ca;
    //unfortunately in this case there remains memory leak

    //Workaroud 3
    //IMHO best long term solution, but it is difficult for me to predict all
    //consequences
    //Allow that typeof(A*) == typeof(A)
    //and typeof(&A) == typeof(A)
    //for classes. It will allow also to create one create function for 
    //all types:
    //T* create(T)() {
    //  return new T;
    //}

    //Workaround 4
    //When creating (new A*)
    //initialize not only first pointer
    //but also second, so that
    // *(new A*) is not null
}


-- 



More information about the Digitalmars-d-bugs mailing list