Creating a copy of the structure heap in D

How can I create a garbage-collected copy of the structure that is on the stack?

Based on the background in C ++, the first assumption would be a copy constructor similar to the one below, but for D it does not seem very idiomatic, and I have not seen any of the D projects that I took a look.

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);
}
+4
source share
2 answers

Your example is too complex and doesn't even compile, but essentially, it looks like what you want to do is something like

struct Foo
{
    int i;
}

void main()
{
    auto f = Foo(5);
    auto g = new Foo(f);
}

What you can do without any special constructors is

void main()
{
    auto f = Foo(5);
    auto g = new Foo;
    *g = f;
}

, , , , . " " D , this(this) {...}, Foo, ( ), - .

auto f = Foo(5);
auto g = new Foo(f);

, , , , . , , , - , . .

struct Foo
{
    int i;

    this(int j)
    {
        i = j;
    }

    this(Foo rhs)
    {
        this = rhs;
    }
}

void main()
{
    auto f = Foo(5);
    auto g = new Foo(f);
}

, new Foo(foo) , dmd ( 2.066), (, new int(5) ), , , .

, .

+8

[s].ptr struct s .

+4

Source: https://habr.com/ru/post/1544550/


All Articles