New With Struct and Getting Class Object Pointers

Vijay Nayar madric at gmail.com
Sun Sep 30 07:29:00 UTC 2018


I have two brief questions.

Code that uses "new" to create struct objects appears to compile 
and run. Is this an actual language feature, to get structs on 
the heap?

void main()
{
	struct S {int data = 1;}
	S* s1 = new S();
	S* s2 = s1;
	S s3 = *s1;  // Still copies on assignment.
	s3.data = 2;
	assert(s1.data != s3.data);
}

Second question. const class variables may not be re-assigned, so 
if you need a variable that may be reassigned, but may never 
modify the underlying object, a const pointer can be useful.  
However, it seems that when gets the address of a class variable, 
you do not get the underlying address of the class object.

How do you get a pointer to the underlying class object?  Example 
of the problem:

void main()
{
	import std.stdio;
	class A { int data = 3; }
	A a = new A();

	void f(A a) {
         a.data = 4;
		writeln("&a = ", &a, ", a.data = ", a.data);
	}
	
     f(a);
     writeln("&a = ", &a, ", a.data = ", a.data);
}

// Output:
&a = 7FFEA6BA3158, a.data = 4  // Addresses are different, from 
different class variables.
&a = 7FFEA6BA3180, a.data = 4  // But the same underlying class 
object.

Especially if I'm several levels down the call stack, how do I 
get a pointer to the underlying class object?


More information about the Digitalmars-d-learn mailing list