为什么从结构数组返回时不调用 this(this) ?
import std.stdio;
struct S
{
string m_str = "defaultString";
this(this)
{
writeln("In this(this)");
}
~this()
{
writeln("In ~this():"~m_str);
}
}
struct Holder
{
S[] m_arr;
S m_s;
this(S[] arr)
{
m_arr = arr;
m_s.m_str="H.m_s";
}
S getSMem()
{
return m_s;
}
S getSVec()
{
return m_arr[0];
}
S getSLocal()
{
S local = S("localString");
return local;
}
}
void main()
{
Holder h = Holder(new S[1]);
S s1 = h.getSMem();
S s2 = h.getSVec();
S s3 = h.getSLocal();
}
上面的 D2.058 给出:
在这个(这个)
在 ~this():localString
在 ~this():defaultString 中
在~this()中:H.m_s
在~this()中:H.m_s
上面只产生了一个 this(this)(来自getSMem() 调用)。 getSLocal() 调用只能移动结构。但是,为什么 getSVec() 不会产生 this(this) 呢?我注意到这是 std.container.Array 中保存的引用计数结构的上下文,与 ~this() 相比,对 this(this) 的调用太少了。
import std.stdio;
struct S
{
string m_str = "defaultString";
this(this)
{
writeln("In this(this)");
}
~this()
{
writeln("In ~this():"~m_str);
}
}
struct Holder
{
S[] m_arr;
S m_s;
this(S[] arr)
{
m_arr = arr;
m_s.m_str="H.m_s";
}
S getSMem()
{
return m_s;
}
S getSVec()
{
return m_arr[0];
}
S getSLocal()
{
S local = S("localString");
return local;
}
}
void main()
{
Holder h = Holder(new S[1]);
S s1 = h.getSMem();
S s2 = h.getSVec();
S s3 = h.getSLocal();
}
The above in D2.058 gives:
In this(this)
In ~this():localString
In ~this():defaultString
In ~this():H.m_s
In ~this():H.m_s
Only one this(this) is produced in the above (from the getSMem() call). The getSLocal() call can just move the struct. However, why does getSVec() not result in a this(this)? I noticed this is the context of a reference counting struct held in a std.container.Array, and there were too few calls to this(this) compared to ~this().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
getSVec
,它看起来像是一个错误,可能与 这个,虽然情况不完全一样。不过,您应该报告您的具体示例,因为它可能不是完全相同的错误。但是,正如您所说,在 getSLocal 的情况下,局部变量会被移动,因此不会发生复制,也不需要 postblit 调用。只是
getSVec
有问题。In the case of
getSVec
, it looks like a bug, possibly related to this one, though the situation is not exactly the same. You should report your specific example though, since it may not be the exact same bug.However, as you say, in the case of
getSLocal
, the local variable is moved, so no copying takes place, and no postblit call is required. It's justgetSVec
which is buggy.