Strict definition of value types and reference types
Nicholas Smith
nmsmith65 at gmail.com
Sat Apr 13 19:18:40 PDT 2013
Two things that I can't seem to nail down a strict definition for
are value types and reference types. I know very well their basic
definitions: a variable of a value type holds its own data and
assignment copies the data, and a variable of a reference type
holds a pointer to its data and assignment (to the same type or a
superclass at least) copies the pointer.
Unfortunately it's easy to find a case where those definitions
don't fit. For example, it is said that slices are reference
types. Sure, slices hold references to an array, but they also
carry their own data, which gives them value semantics. For
example, below I introduce my new integer type which I think we
can all agree should be part of the D language.
import std.stdio;
alias Integer = void[];
void main()
{
Integer num1, num2;
write("Enter two non-negative numbers to add separated by a
space: ");
size_t v1, v2;
readf(" %s %s\n", &v1, &v2);
num1.assign(v1);
num2.assign(v2);
Integer result = num1.add(num2);
writeln("Answer: ", result.toSize_t());
}
Integer assign(ref Integer lvalue, size_t rvalue)
{
lvalue.length = rvalue;
return lvalue;
}
Integer add(Integer num1, Integer num2)
{
Integer result;
result.assign(num1.toSize_t() + num2.toSize_t());
return result;
}
size_t toSize_t(Integer num)
{
return num.length;
}
In essence, are not all types just structs, with different
operator overloads to give different semantics? If so, how do we
classify 'value type' versus 'reference type'? What if I have a
struct whose members are a fixed-length array and a slice, and
different operations act on different members? The only thing I
can really consider to be a reference type is a plain reference
to an instance of a class.
More information about the Digitalmars-d-learn
mailing list