1
votes

https://dlang.org/spec/expression.html says "If a NewExpression is used as an initializer for a function local variable with scope storage class, and the ArgumentList to new is empty, then the instance is allocated on the stack rather than the heap or using the class specific allocator."

Does it mean that in the following program an object of C is allocated entirely on the stack, without any heap allocation?

class C {
  int x;
}

void main() {
  scope c = new C();
}

Also: Why does it work only for empty argument list?

I doubt that I understand correctly, because all the rest D materials I read say that classes are allocated on the heap. I want to make sure.

1
"Why does it work only for empty argument list?" That is the arguments to new itself (which is rarely used), which are separate from arguments to the class constructor.Adam D. Ruppe

1 Answers

3
votes

In D, generally, classes are allocated on the heap. In this one specific case, classes can be allocated on the stack.

The specific case is:

  • The variable is initialized with a call to new SomeClass
  • No references to that value escape the current function (scope)
  • The initialization doesn't involve a custom allocator (which is deprecated); that would look like new(args) SomeClass.