References
In addition to pointers, Spice supports references. Under the hood, this works with non-nullable pointers.
Usage - local variables¶
References can not be declared without initializing. Only declaring with immediate initialization is valid:
| Spice | |
|---|---|
Whenever an assign operator is applied to the reference, not the reference is mapped to a new variable. Instead, the referenced value gets assigned. Therefore, the reference itself can only be assigned once, namely at declaration.
Usage - function parameters / return types¶
References can be used as function parameters and return types. This is useful for passing large objects without copying them:
| Spice | |
|---|---|
Usage - struct fields¶
Struct fields can also be of type reference:
| Spice | |
|---|---|
Usage - ternary expressions¶
If both operands of a ternary expression are lvalues (variables, fields, ...), the result is a reference to the selected operand. It can be bound to a non-const reference and modified through it, without copying anything:
| Spice | |
|---|---|
If at least one operand is a temporary value (e.g. a literal or the result of a function call), the ternary expression yields a copy of the selected operand instead. Such a value can only be bound to a const reference. If only one of two lvalues is const, the result is a const reference, so it can not be bound to a non-const reference either.