12.6.7.12 CPP0011 - Promoted Stack Only Value Type

Description

Extern classes or enums annotated with cpp.ValueType and which contain the StackOnly flag are forbidden from being promoted to the heap. There are many ways a type can be silently promoted to the heap, the following examples show a few such cases.

Examples

The following examples generate CPP0011.

@:semantics(value)
@:cpp.ValueType({ flags : [ StackOnly ] })
extern class Foo {
    function new():Void;
}

function main() {
    final f : Null<Foo> = new Foo(); // CPP0011, nullable value types are required to go on the heap.
}
@:semantics(value)
@:cpp.ValueType({ flags : [ StackOnly ] })
extern class Foo {
    function new():Void;
}

function main() {
    final f = new Foo(); // CPP0011, variables captured in a closure are required to go on the heap.
    final c = () -> {
        trace(f);
    }

    c();
}
@:semantics(value)
@:cpp.ValueType({ flags : [ StackOnly ] })
extern class Foo {
    function new():Void;
}

function bar(o:Dynamic) {
    trace(o);
}

function main() {
    final f = new Foo(); // CPP0011, converting a value type to Dynamic requires boxing it onto the heap.
    
    bar(f);
}
@:semantics(value)
@:cpp.ValueType({ flags : [ StackOnly ] })
extern class Foo {
    function new():Void;
}

class Bar {
    var f : Foo; // CPP0011, class fields of value types are required to be on the heap.

    public function new() {
        f = new Foo();
    }
}

function main() {
    final f = new Bar();
}