Syntax for Pointer to Class
Q. Schroll
qs.il.paperinik at gmail.com
Fri Jan 25 20:52:56 UTC 2019
On Friday, 25 January 2019 at 20:31:29 UTC, H. S. Teoh wrote:
> 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.
>
> Note that taking the address of `C` will actually give you a
> pointer to the reference, not the pointer to the class instance
> itself.
I know. This is precisely the thing I asked for: A pointer to a
handle. I called it handle for exactly this reason.
> 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
Yes. `&new C(...)` looked to wrong for me to even consider trying.
> C c = new C(...);
> C* ptrToRef = &c;
So the answer is no. At least not that simple.
> 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.
That's kind of obvious if you get remembered, but thanks. I
wasn't considering this as I wanted the handle to live on the
heap anyway --- the same way for a struct `S`, the pointer
pointed to by `S** ptr = new S*(new S(...));` lies on the heap.
I'll use
C* ptr = &[ new C(...) ][0];
for now. It looks ugly, but it does the job.
More information about the Digitalmars-d-learn
mailing list