适当的教堂所有权

  • 本文关键字:所有权 教堂 chapel
  • 更新时间 :
  • 英文 :


用于在init中创建的对象字段的适当所有权是什么?我认为最好使用"拥有",但看起来它在启动结束后没有保留这些东西。

运行此代码...(在线尝试!)

class Name {
    var text : string;
    //initializer
    proc init(name : string) {
        this.text = name;
    }
        proc writeThis(writer) {
        writer.writeln(this.text);
    }   
} //end of Name
class Monkey {
        var name : Name;
        var age : int;
        proc init(name : string, age : int) {
            this.name = new owned Name(name);
            this.age = age;
        }
    proc writeThis(writer) {
        writer.writeln("I'm a monkey named ", this.name, ", and I'm ", this.age, " years old.");
    }
} //end of class Monkey

var m = new owned Monkey("bananaface", 5);
writeln("m: ", m);

...使其仅打印:

m: I'm a monkey named 

在线尝试!

在猴子的初始化中,比设置此更合适的所有权。name= new拥有名称(...)?

我尝试了您的程序,并使用预释放1.19版(即将发布),然后打印出来

monkeys.chpl:20: In initializer:
monkeys.chpl:21: error: Field name would outlive the value it is set to

现在我将解释问题:

class Name { ... }
class Monkey {
  var name : Name;
  proc init(name : string) {
    this.name = new owned Name(name);
  }
}

等于

class Name { ... }
class Monkey {
  var name : borrowed Name;
  proc init(name : string) {
    this.name = new owned Name(name);
  }
}

相同
class Name { ... }
class Monkey {
  var name : borrowed Name;
  proc init(name : string) {
    var tmp = new owned Name(name);
    this.name = tmp.borrow();
    // the instance in tmp is automatically deleted here
  }
}

,您也许可以更清楚地看到new owned的结果在初始化器的末尾被破坏。

修复很简单:将字段声明为 var name: owned Name;

class Name { ... }
class Monkey {
  var name : owned Name;
  proc init(name : string) {
    this.name = new owned Name(name);
  }
}

相关内容

  • 没有找到相关文章

最新更新