在牛肉中,我可以使用以下代码:
using System;
namespace Program
{
class Foobar
{
public int value;
public this(int val)
{
value = val;
}
public static Foobar operator+(Foobar lhs, Foobar rhs)
{
let result = new Foobar();
result.value = lhs.value + rhs.value;
return result;
}
}
class Program
{
public static void Main()
{
Foobar a = scope:: Foobar(5);
Foobar b = scope:: Foobar(5);
Foobar c = a + b;
defer delete c;
Console.Write("{}", c.value);
Console.In.Read();
}
}
}
这很好用,因为我可以轻松地删除a+b
操作所做的堆分配。但是,如果我有:
using System;
namespace Program
{
class Foobar
{
public int value;
public this(int val)
{
value = val;
}
public static Foobar operator+(Foobar lhs, Foobar rhs)
{
let result = new Foobar();
result.value = lhs.value + rhs.value;
return result;
}
}
class Program
{
public static void Main()
{
Foobar a = scope:: Foobar(5);
Foobar b = scope:: Foobar(5);
Foobar x = scope:: Foobar(20);
// Foobar c = (a + b) + x; // would leak
Foobar temp = a + b;
defer delete temp;
Foobar c = temp + x;
defer delete c;
Console.Write("{}", c.value);
Console.In.Read();
}
}
}
我必须一次添加一个并一次删除每个结果。
有没有更好的方法来处理这些临时变量的破坏?