0
点赞
收藏
分享

微信扫一扫

d结构用要求


​​原文​​

import std;

struct A
{
double val;
bool isBig;
}


void main() {
alias DListOfA = DList!A;
DListOfA[string] temp;
A a = {2.0, true};

DListOfA returnVal = temp.require("a", DListOfA());//--> 这里希望用DListOfA的引用

returnVal.insert(a);
writeln(temp);
}

​​参考​​ 希望能够这样:

ref DListOfA returnVal = ....

但是不能​​保持​​​临时引用,因为临时在该表达式的末尾结束(实际上是在分号处).
或者用​​​new​​​动态分配对象(并将​​DListOfA*​​​存储在关联数组中).然后,只要​​指针​​​在关联数组中,​​GC​​​就会让它保持活动状态.
更好选择是忘记它,因为D已经通过默认​​​blitting​​​(位级复制)来处理​​右值​​​.一切正常…:)它也不贵.例如,复制结构很便宜.
但我可能错过了你想要​​​ref​​的原因.也许还有更好的选择.

使用指针:

DListOfA *returnVal = &temp.require(...);
returnVal.insert(a);

这样:

import object, std.container;

struct A
{
double val;
bool isBig;
}

void main()
{
alias DListOfA = DList!A;
DListOfA returnVal;
//DListOfA[string] temp;
DListOfA[string] temp = [
"a": DListOfA( A(0) )
];//*/

auto a = A(6, true); // replacement element
temp.update("a", {
return DListOfA( A(0) ); // not updated: unsucceeded but initialized
}, (ref DListOfAv) {
v = DListOfA( a ); // existing v has been replaced
returnVal = v;
assert(returnVal.front == a);
});
assert(is(typeof(temp["a"]) == DList!A));
}


举报

相关推荐

0 条评论