On 2010-09-17 11:14:21 -0400, Andrei Alexandrescu
<[email protected]> said:
On 9/17/10 9:18 CDT, Michel Fortin wrote:
On 2010-09-17 04:15:31 -0400, Andrei Alexandrescu
<[email protected]> said:
On a funny note, we figured that for a number of reasons it would help
to allow C++-style constructors that offer access to the source; it
just turns out some idioms need to modify the source as well as the
destination.
One obvious example is the built-in hashtable that is not shared
properly when it's null. Making the copy constructor spring the
hashtable to life would make it more uniform in behavior.
At the basic level I feel uneasy with this whole idea of modifying the
source while copying. It means that you can't copy the source if it is
const. Do you really want to make const containers uncopyable?
Again, the scenario is motivated by this:
void main()
{
int[int] hash;
fun(hash);
assert(!(42 in hash));
hash[0] = 10;
fun(hash);
assert(42 in hash);
}
void fun(int[int] hash)
{
hash[42] = 42;
}
Walter's idea was as follows. If the hash's copy constructor has access
to the source, then that constructor could lazily initialize the
pointer internally shared by the existing instance (the one in main())
and the one being created (the one passed to fun()). Then, the program
would behave more predictably and also stay efficient - lazy
initialization for the win.
I understand the intent quite well. I'm talking about what happens if
the source is const? As in:
struct A {
int[int] hash;
int[int] fun() {
return hash; // hash can be altered, can copy
}
const const(int[int]) fun() {
return hash; // here hash is const, what happens?
}
}
With the second accessor the hash is const, so how can you copy it
anywhere if copying requires altering the original? Should it be an
error? Should the copy be detached when the source is const, breaking
reference semantics? Or should we add logical-const (in addition to
C++-style constructors)?
Now that I think of it, you don't need a fancy struct to make this
problem appear, you just need two layers of functions:
void fun(const(int[int]) hash) {
fun(hash); // calling ourself, how can we copy hash?
}
Although in this case we could probably assert() that hash is already
initialized.
In my mind it's simpler to just explain the notion that an
uninitialized hash is null and detached from anything else until
initialized. Objects works like this (minus the implicit initialization
part), so it shouldn't be too hard to understand. Better have pragmatic
semantics that work rather than idealistic semantics that fail at a
number of cases.
--
Michel Fortin
[email protected]
http://michelf.com/