DIP1000

Loara loara at noreply.com
Thu Jun 30 19:56:38 UTC 2022


On Tuesday, 28 June 2022 at 21:58:48 UTC, Ola Fosheim Grøstad 
wrote:
> Not when connect returns, but the scope that connect was called 
> from. Still, this can be deduced, you just have to give the 
> scopes an ordering.

The deduction can happen even if you don't use `scope` attribute. 
When you use `scope` attribute you're saying to compiler "You 
have to allocate this object on the stack, don't try to use heap 
allocation". If you want to let compiler to decide what is the 
best approach then don't use `scope`.

> Well, that is a flaw, if the object is stack allocated then the 
> fields are too.

No because:

`scope` variable === the variable is a pointer/reference that 
points to stack allocated data

So `scope int v;` is equal to `int v;` since `v` is not a 
pointer, whereas `scope int *p` is different from `int *v;` since 
the latter can't point to stack allocated integers. This is the 
difference.

Since stack allocated objects are destroyed in the reverse order 
allowing a recursive `scope` attribute is a bit dangerous as you 
can see in the following example:

```d

struct A{
   int *i;

   ~this(){
     writeln(*i);
   }
}
...
  {
   A a;
   int i = 2;
   ...
   scope int *j = &i;
   scope A *b = &a;
   (*b).i = j;
  } // i is destroyed before a
```

> The compiler could easily deduce it. It is not difficult to see 
> what the life time constraint must be.

Again if you want to let the compiler to deduce then don't use 
`scope`.




More information about the Digitalmars-d-learn mailing list