Problem with taking inout, const references
Ali Çehreli
acehreli at yahoo.com
Wed Mar 26 14:11:51 PDT 2014
On 03/26/2014 12:17 PM, Uranuz wrote:
> I modified this with casting pointer to pointer to *inout* and it
> compiles then.
>
> inout(Cookie)* opBinaryRight(string op)(string name) inout if(op == "in")
> { foreach( ref inout(Cookie) c; _cookies )
> if( c.name == name )
> return cast(inout(Cookie)*) &c; //Error is here
> return null;
> }
I think it is a bug then. I only now understand the problem. Here is a
reduced case:
class C
{
int[1] arr;
inout(int)* foo() inout
{
foreach (ref e; arr) {
static assert(is (typeof(e) == inout(const(int)))); // WAT?
return &e;
}
}
}
void main()
{
(new C).foo();
}
The problem is, when the foreach variable is ref, the type gains a const
as well. Unless there is a reason for that we should file a bug.
Another workaround for you is using the foreach index:
{ foreach(i, ref inout(Cookie) c; _cookies ) // NOTE i
if( c.name == name )
return &_cookies[i]; // NOTE i
return null;
}
> As I think compiler may be should create const version and mutable
> version of this function.
Type is a compile-time concept; there is no difference between the
compiled mutable versus const versions of your inout function. So, there
is no need for more than one compilation.
> In case when it's mutable it should return pointer to mutable
> pointer to *const* data when function is const.
Makes sense and it should be checked at compile time.
> I don't understand why compiler produce pointer to const,
I think that's a bug.
> In case when all is treated like const
The body of an inout function must not mutate the object because the
same body supports the non-mutable cases as well. So, it is acceptable
for the compiler to compile as if it's const. However, as you say, the
interface of the function still obeys the actual types used in the program.
You are right. I think it is just a bug.
Ali
More information about the Digitalmars-d-learn
mailing list