转义对局部变量的引用

Escaping reference to local variable

我是D语言的新手。在尝试创建一个 return 字节数组的简单函数时,我 运行 在尝试 return 我的值时出错。有没有不同的方法我应该 return 来自函数的局部变量?

在 return 行,我得到错误 Error: escaping reference to local c

我的代码:

byte[] xorFixed(byte[] a, byte[] b){
   if (a.sizeof != b.sizeof) return null;
   byte[a.sizeof] c;
   for (int i = 0; i < a.sizeof; i++)
   {
      c[i] = (a[i] ^ b[i]);

   return c;
}

byte[]byte[some_size] 是两种不同的类型。 byte[some_size] 是静态数组,在使用时被复制,byte[] 是指向其值的切片或动态数组。

当您尝试 return c 时,由于 return 值是一个切片,它会尝试获取指向 c...当函数 returned 时存在。如果这个编译,它会给你乱码或在运行时崩溃!

您需要修正类型。 c 应该 而不是 byte[a.sizeof]。它应该只是一个普通的 byte[]。要设置数组的大小,请使用 .length 而不是 .sizeof

if (a.length != b.length) return null; // changed sizeof -> length
byte[] c; // changed type
c.length = a.length; // this sets the length of c to match a
for (int i = 0; i < a.length; i++) // changed sizeof to length

这将如您所愿。

更惯用的 D 代码示例:

ubyte[] xor(in ubyte[] a, in ubyte[] b)
{
    assert(a.length == b.length);

    auto c = new ubyte[a.length];

    return c[] = a[] ^ b[];
}