New With Struct and Getting Class Object Pointers

Vijay Nayar madric at gmail.com
Sun Sep 30 10:41:06 UTC 2018


On Sunday, 30 September 2018 at 10:28:25 UTC, Alex wrote:
> On Sunday, 30 September 2018 at 09:30:38 UTC, Vijay Nayar wrote:
>> Is there a way to either have a constant reference to a class 
>> that can be set to a new value, or is there a way to convert 
>> the class variable to a class pointer?
>
> I think, what you are facing here, is the different notion of 
> const, as used from C++. The reasoning about it is described 
> for example here:
> http://jmdavisprog.com/articles/why-const-sucks.html
> Jonathan is much better therein as I am.
>
> However, there are approaches to solve what you want to do. For 
> example, there is a Rebindable around:
> https://dlang.org/library/std/typecons/rebindable.html
>
> ´´´
> import std.stdio;
> import std.typecons;
>
> void main()
> {
> 	class Thing {int dummy; }
> 	class ThingSaver {
>                 /*
> 		A const(Thing) could not be changed in setThing(),
> 		but a Rebindable can be reassigned, keeping t const.
> 		*/
> 		Rebindable!(const Thing) t;
>
> 		void setThing(in Thing thing) {
> 			t = thing;  // No pointers in use :)
> 		}
> 		const(Thing) getThing() const {
> 			return t;
> 		}
> 	}
> 	
> 	Thing t1 = new Thing();
>
> 	ThingSaver saver = new ThingSaver();
> 	saver.setThing(t1);
> 	//saver.t.dummy = 5; fails as expected.
> 	const(Thing) t2 = saver.getThing();
> }
> ´´´
> I hope, I got your idea right...

That pretty much hits the nail on the head, and you're exactly 
right about where my understanding was coming from (C++).  In 
fact, I'm moving a lot of code from C++ to D and finding 
equivalents for a lot of high-performance index classes, which 
end up using this kind of pattern.

Now I need to take the time to grok this article!



More information about the Digitalmars-d-learn mailing list