Const-correctness in D

class Foo
{
int x = 10;
}
const(Foo) foo = new Foo();
foo.x = 5; // illegal!
class Foo
{
int x = 10;
}
int bar(Foo foo1, Foo foo2)
{
return foo1.x + foo2.x;
}
void main()
{
immutable(Foo) foo1 = new Foo();
Foo foo2 = new Foo();
bar(foo1, foo2);
}
int bar(const(Foo) foo1, const(Foo) foo2)
{
return foo1.x + foo2.x;
}
const int x = 10;
int* px = cast(int*)&x;
*px = 5;
auto halfArray(const(int)[] a)
{
return a[$/2..$];
}
immutable(int)[] arr1 = [4, 5, 7, 8];
immutable(int)[] arr2 = halfArray(arr1);
auto halfArray(inout(int)[] a)
{
return a[$/2..$];
}
const(int)[] arr1 = [4, 5, 7, 8];
const(int)[] arr2 = halfArray(arr1);
int[] arr1 = [4, 5, 7, 8];
int[] arr2 = halfArray(arr1);
class Foo
{
int prop() const
{
return _prop;
}
protected int _prop = 0;
}
class Foo
{
int prop() const
{
_prop = 8;
return _prop;
}
protected int _prop = 0;
}
import std.string;class Foo
{
const(char*) prop() const
{
return _prop.toStringz();
}
protected string _prop = "something";
}
void foo(ref const(int) v)
{
v = 0; // illegal
}
int[] arr = [1, 2, 3, 4, 5];foreach(ref const v; arr)
{
foo(v);
v = 0; // illegal
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store