Variable assignment

Derek Parnell derek at psych.ward
Mon Mar 26 15:01:59 PDT 2007


On Mon, 26 Mar 2007 13:19:13 -0400, okibi wrote:

> I've been writing an xml editor and testing some code. I ran into this problem with 1.006+ (didn't have the problem in 1.00, jumped straight to 1.006 after that).
> 
> The problem is declaring variables in a class, and then setting them within a
> function inside the class. For example, I declare both var1 and var2. I use
> an open function and set var1 to the file selected. Then I run an export
> function and set var2 to that file. When I issue the save function afterwords,
> var1 was adjusted to the same value as var2. I found out that this happens
> while setting var2.
> 
> Any tips or do you need more info?

This sounds like you are doing this, in effect.

  char[] var1;
  char[] var2;

  var1 = filename;
  . . .
  filename = something;
  . . .
  var2 = filename;
  . . .
  // Now var1 == var2;

If so, then remember that assigning to an array only makes both arrays
point to the same data in RAM. If you later change that source array in a
way that doesn't make it allocate new RAM, you still have both vars
pointing to the same RAM.

Try ".dup" if you really need to assign data from an array rather than copy
the reference.

  char[] var1;
  char[] var2;

  var1 = filename.dup;
  . . .
  filename = something.dup;
  . . .
  var2 = filename.dup;
  . . .
  // Now var1 != var2;

-- 
Derek Parnell
Melbourne, Australia
"Justice for David Hicks!"
skype: derek.j.parnell


More information about the Digitalmars-d-bugs mailing list