Syntax for Pointer to Class
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Jan 25 20:31:29 UTC 2019
On Fri, Jan 25, 2019 at 08:12:33PM +0000, Q. Schroll via Digitalmars-d-learn wrote:
> Say I have a class C and I want a pointer to a C handle.
>
> I tried the following pieces of syntax:
>
> C* obj = new C(); // gives me a C
> C* obj = new C*(); // gives me a C**
> C* obj = C*(); // refuses to compile
>
> Is it even possible? This sounds so newbie...
> I know it's fairly simple with structs: S() gives me a struct
> instance, new S() gives me a ptr to a struct instance.
Classes in D are inherently by-reference, meaning that if you have a
class:
class C { ... }
then the type `C` is implicitly a pointer to the class instance. Of
course, this is hidden by the language syntax so most of the time you
don't have to care that it's a pointer, just that it has reference
semantics.
If you want the raw pointer to the class instance, just cast the
reference to void*, for example:
C c = new C(...);
void* ptr = cast(void*) c;
Note that taking the address of `C` will actually give you a pointer to
the reference, not the pointer to the class instance itself. For that to
be valid, you'll need to store your class reference somewhere first,
since it's invalid to take the address of an rvalue:
C c = new C(...);
C* ptrToRef = &c;
// And you'll need to explicitly dereference the pointer to get
// to the class instance:
(*ptrToRef).method(...);
Be warned that the pointer will become invalid when the reference `c`
goes out of scope, even if the object itself is still live (via another
reference), because the pointer is pointing to the class reference
rather than the actual object.
T
--
Once the bikeshed is up for painting, the rainbow won't suffice. -- Andrei Alexandrescu
More information about the Digitalmars-d-learn
mailing list