Returning a ref to a temporary already possible?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 22 22:24:40 PDT 2014


On Thu, Oct 23, 2014 at 10:39:34AM +0530, Shriramana Sharma via Digitalmars-d-learn wrote:
> IIUC the whole deal with not allowing ref parameters to point to
> rvalues is the fear that they may be returned outside the function,
> but it seems this is already possible:
> 
> module reftest ;
> import std.stdio ;
> struct Pair {
> 	int x, y ;
> 	this (int x_, int y_) { x = x_ ; y = y_ ; writeln("Pair constructed") ; }
> 	auto handle() { return this ; }
> }
> void main() {
> 	auto P = Pair(1, 2).handle ;
> 	writeln(typeof(P).stringof) ;
> 	P.x = 3 ;
> 	writeln(P.x, ' ', P.y) ;
> }
> 
> Running this makes it clear that only the one Pair object is ever
> constructed. But I don't understand how it is that the type of P is
> Pair and not ref(Pair).
[...]

ref is a storage class, not a type constructor. There is actually no
such type as ref(Pair).  The 'ref' applies only to the function
parameter (or return value), NOT to whatever it gets assigned to.


T

-- 
Microsoft is to operating systems & security ... what McDonalds is to gourmet cooking.


More information about the Digitalmars-d-learn mailing list