New With Struct and Getting Class Object Pointers

Nicholas Wilson iamthewilsonator at hotmail.com
Sun Sep 30 09:16:42 UTC 2018


On Sunday, 30 September 2018 at 07:29:00 UTC, Vijay Nayar wrote:
> 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?

the variable `a` is a pointer (well, actually reference) to the 
underlying data.

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

	void f(A a) {
         a.data = 4;
		printf("&a = %p, a = %p, a.data=%d\n", &a, a,a.data);
	}
	
     f(a);
     printf("&a = %p, a = %p, a.data=%d\n", &a,a, a.data);
}

&a = 0x7ffd0800acb8, a = 0x7fd6b05b0000, a.data=4
&a = 0x7ffd0800acd0, a = 0x7fd6b05b0000, a.data=4

      The stack ^                     the heap^          data on 
the heap^
The address of the variable a on the stack has different values 
across function calls, its value (the reference to the class 
data) remains the same, as does the data itself.



More information about the Digitalmars-d-learn mailing list