如何创建堆栈中的结构的垃圾收集副本?
来自C++背景,我的第一个猜测将是一个像下面那样的复制构造函数,但对于D来说它似乎不是很惯用,而且我没有在任何D项目中看到过我看过的.
struct Foo {
immutable int bar;
this(int b) { bar = b; }
// A C++-style copy constructor works but doesn't seem idiomatic.
this(ref const Foo f) { bar = f.bar; }
}
void main()
{
// We initialize a Foo on the stack
auto f = Foo(42);
// Now I want to get a heap copy of its member. How?
// A C++-style copy constructor works but doesn't seem idiomatic.
Foo* f1 = new Foo(f);
}
Run Code Online (Sandbox Code Playgroud)