On Wednesday, 29 August 2012 at 14:17:21 UTC, Era Scarecrow wrote:
Then most of my examples change to going into the constructor
rather than out, and the global one goes away. But it still
doesn't help with the problem of anything stack allocated.
struct S {
//default construtor otherwise then fails to work because of
ref? Since
//x must be known at compile time so it would be null to
start with, or no
//default onstructor
ref int x;
this(ref int r) { x = r;}
}
S func() {
int local = 42;
S s = S(local);
return s;
}
S func(ref int reffed) {
S s = S(reffed);
return s;
}
S s = func();
writeln(s.x); //mystery value still!
{
int local = 42;
s = func(local);
writeln(s.x); //42
}
writeln(s.x); //!?!?
Unless I'm understanding this wrong (And I'm tired right now
maybe I missed something), once again the only safe 'reference
variable' is from actively being called from a live accessible
reference; And anything else is still a ticking timebomb and
cannot ever be @safe. Stuff referencing within heaped/class
related stuff may suffer fewer problems, but only as long as
you rely on the GC and not do any magic involving malloc/free,
or maybe a dynamic range.
Reminds me. The example for the foreach are missing parts.
int[10] fixed;
int[] dynamic;
dynamic.length = 10;
foreach(i; fixed) {
//fine, i is a copy
}
foreach(ref i; fixed) {
//compile-time error for @safe checking
//cannot ensure this is safe otherwise
}
foreach(i; dynamic) {
//fine, i is a copy
}
foreach(ref i; dynamic) {
//Dynamic/heap allocated, so fine.
}
//from function/ref
void func(int[] huh) {
foreach(ref i; huh) {
//????? safe?
}
}
//both legal last I checked.
func(fixed);
func(dynamic);
My god, as I look at this more, reference variables would
cripple D so badly C++ wouldn't look half bad afterwards.
I honestly don't know anything about memory safety and what it
entails. So, I can't comment about any of that stuff. But if you
say general ref variables can't be implemented in @safe mode,
then I can just take your word for it. But what I'm saying is
that ref variables would be a nice feature to have in @system
code.
My logic is very simple: since we can use pointers in @system
code, and references are no more unsafe than pointers, then we
should be able to use references in @system code. You might argue
that references are little more than syntactic sugar (and a bit
safer) compared to pointers, but you shouldn't underestimate the
importance of syntactic sugar especially when you're trying to
lure in users of C++.