www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - A proposal that has nothing to do with const

reply BCS <BCS pathlink.com> writes:
I was talking to a friend of mine and a coding problem he was working on 
required a proxy type. While looking at his C++ implementation and 
comparing it to D (he liked D's BTW) it occurred to me that it would be 
hand to have a way to say "this type may not be assigned to a variable 
outside of this code". It would be like the type is public when used as 
a temporary but when used as a variable, it would be private.

Say C has this property:

//code with private access to C

class C
{
	C opAdd(C);
	int opImplicetCast();
}

C GetC();
void UseC();

// code with public access to C


UseC(GetC()); // valid
UseC(GetC() + GetC()); // valid

int i = GetC(); //valid

C c1; // invalid
auto c2 = GetC(); // invalid

struct S
{
	C c3; // invalid
}

void foo(C c4); // invalid
C bar(); // invalid

This would aid in things like escape analysis. because you can't have a 
named variable of the given type, you can't hold onto it. This would 
make returning a "reference wrapper" as a proxy safe(er) because you 
known that the calling code can't allow it to escape passed where you 
were called. The closest they can get is to pas it back to you, and then 
you are responsible for keeping things safe.

One case that I'm not sure if should be allow is "with":

with(GetC())
{
	// do several things to C
}

P.S. Mostly I'm throwing this out as foot for though. It might be to 
much of a corner case to get added but it might seed some other ideas or 
get built as part of some other feature.
Dec 07 2007
next sibling parent Gregor Richards <Richards codu.org> writes:
<troll>
But what if you have a const C?

  - Trollor Richards
</troll>
Dec 07 2007
prev sibling parent reply Jason House <jason.james.house gmail.com> writes:
BCS wrote:
 it occurred to me that it would be
 hand to have a way to say "this type may not be assigned to a variable
 outside of this code".
I usually view scope in this way... If a variable is passed into functions as a scope, it can't use it past the end of the function call.
Dec 09 2007
parent BCS <ao pathlink.com> writes:
Reply to Jason,

 BCS wrote:
 
 it occurred to me that it would be
 hand to have a way to say "this type may not be assigned to a
 variable
 outside of this code".
I usually view scope in this way... If a variable is passed into functions as a scope, it can't use it past the end of the function call.
I don't think that is strong enough. You can still declare a variable of that type in any code that can get access to something of that type. If the type can be returned to you, than you can return it your self.
Dec 09 2007