Copy a struct and its context
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 12 18:32:19 PDT 2016
On 9/12/16 4:11 PM, Ali Çehreli wrote:
> On 09/10/2016 10:44 PM, Yuxuan Shui wrote:
>> I recently noticed nested struct capture its context by reference
>> (which, BTW, is not mentioned at all here:
>> https://dlang.org/spec/struct.html#nested).
" It has access to the context of its enclosing scope (via an added
hidden field)."
It needs to be a reference. Otherwise, you store the entire stack frame
in the struct? That wouldn't be a "field". It also has write access to
the context:
void foo()
{
int i;
struct S {
void changeI(int newVal) { i = newVal; }
}
S s;
s.changeI(10);
assert(i == 10);
}
The documentation could be clearer.
> And bliting a struct
>> obviously doesn't do a deep copy of its context.
>>
>> So my question is, is there a way to deep copy the context of a struct?
>
> Can you show a small example? This seems to work:
>
> auto foo(int i) {
> struct S {
> int foo() {
> return i;
> }
> }
>
> return S();
> }
>
> void main() {
> auto s = foo(42);
> auto s_copy = s;
> assert(s.foo() == 42);
> assert(s_copy.foo() == 42);
> }
He wants to deep-copy the struct, meaning copy the context pointer data.
Meaning if you change 'i' in s, then s_copy's foo still returns 42.
I don't think it is or should be doable.
-Steve
More information about the Digitalmars-d-learn
mailing list