www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Passing an array by reference?

reply "Rishub Nagpal" <rishubster gmail.com> writes:
   1 class Test
   2 {
   3     int[][] array;
   4     this(ref int[][] d)
   5     {
   6         array = d;
   7     }
   8
   9 }
  10
  11 void main()
  12 {
  13     Test t = new Test([[1,1],[1,1]]);   //does not compile
  14 }
  15


what is the best way to pass a literal ([[1,2],[3,4]]) by 
reference? Is using ref the best way? I am still a bit fuzzy with 
in/out and scope
Jul 24 2014
parent reply "John Colvin" <john.loughran.colvin gmail.com> writes:
On Thursday, 24 July 2014 at 16:06:00 UTC, Rishub Nagpal wrote:
   1 class Test
   2 {
   3     int[][] array;
   4     this(ref int[][] d)
   5     {
   6         array = d;
   7     }
   8
   9 }
  10
  11 void main()
  12 {
  13     Test t = new Test([[1,1],[1,1]]);   //does not compile
  14 }
  15


 what is the best way to pass a literal ([[1,2],[3,4]]) by 
 reference? Is using ref the best way? I am still a bit fuzzy 
 with in/out and scope
Why do you need to pass the array by reference? D's slices are just windows on to memory, they don't copy the contents when you pass them around. Anyway, if you do need ref, the problem is that [[1,1],[1,1]] is a temporary, an rvalue, and ref can't take rvalues.
Jul 24 2014
parent "Rishub Nagpal" <rishubster gmail.com> writes:
On Thursday, 24 July 2014 at 16:15:44 UTC, John Colvin wrote:
 On Thursday, 24 July 2014 at 16:06:00 UTC, Rishub Nagpal wrote:
  1 class Test
  2 {
  3     int[][] array;
  4     this(ref int[][] d)
  5     {
  6         array = d;
  7     }
  8
  9 }
 10
 11 void main()
 12 {
 13     Test t = new Test([[1,1],[1,1]]);   //does not compile
 14 }
 15


 what is the best way to pass a literal ([[1,2],[3,4]]) by 
 reference? Is using ref the best way? I am still a bit fuzzy 
 with in/out and scope
Why do you need to pass the array by reference? D's slices are just windows on to memory, they don't copy the contents when you pass them around. Anyway, if you do need ref, the problem is that [[1,1],[1,1]] is a temporary, an rvalue, and ref can't take rvalues.
Ah I did not know that. jwhear on IRC cleared it up for me http://dpaste.dzfl.pl/c7ae7e71d45c
Jul 24 2014