In the following example code there's a situation, where the data
we're looking for already exists, the data has value semantics,
finding the data takes quite a lot of time, we need to "use" the
data on multiple occasions, and the size of the data is so large
that we don't want to copy it.
In this situation, I think, the most convenient and sensible
thing to do is to make a reference to the data, and use that
reference multiple times. We could make a pointer, but then we'd
be stuck with the nasty syntax of dereferencing:
struct Book // has value semantics
{
// ... lots of data
void read() const
{
// ...
}
}
struct NationalLibrary
{
immutable Book[] _books;
ref immutable(Book) find(string nameOfBook)
{
auto idx = 0;
// ... takes quite long to figure out the index
return _books[idx];
}
}
void main()
{
NationalLibrary nl;
// This is fine if we just want to read it once:
nl.find("WarAndPeace").read();
// ... but if we want to read it multiple times, we don't want
// to each time go to the library and take the time to find
it:
immutable(Book)* ptrWarAndPeace = &nl.find("WarAndPeace");
// And now we're stuck with this syntax:
(*ptrWarAndPeace).read();
(*ptrWarAndPeace).read();
// I'd like to be able to do this:
// ref immutable(Book) refWarAndPeace =
nl.find("WarAndPeace");
// refWarAndPeace.read();
// refWarAndPeace.read();
}
Foreach loops can make reference variables, and function calls
can do it for the parameters passed in. So, my question is,
wouldn't it be better if we could, in general, make reference
variables?