Can Scope Be Used for Anonymous Objects?

Ali Çehreli acehreli at yahoo.com
Wed Oct 17 20:41:24 UTC 2018


On 10/17/2018 01:24 PM, Vijay Nayar wrote:
> I have a snippet of code like this:
>      scope chordAngle = new S1ChordAngle(_center, other._center);
>      return _radius + other._radius >= chordAngle;
> 
> The reason the "scope" temporary variable exists is to avoid a heap 
> allocation and instead prefer a value be created on the stack.  Is there 
> a way to do this inline?
> 
> Something like:
>      return _radius + other._radius >= scope new S1ChordAngle(_center, 
> other._center);

I think it's possible but what you're looking for is 
std.typecons.scoped. 'scope' does not do what you think it does.

import std.typecons : scoped;

class C {
     int i;
     this(int i) {
         this.i = i;
     }
     int foo() {
         return i;
     }
}

bool bar() {

     auto c = scoped!C(42);
     return 42 == c.foo();
}

bool bar_2() {
     return 42 == scoped!C(42).foo();
}

void main() {
     bar();
     bar_2();
}

Ali


More information about the Digitalmars-d-learn mailing list