Auto keyword with const variable
monarch_dodra
monarchdodra at gmail.com
Wed Jul 24 03:54:31 PDT 2013
On Wednesday, 24 July 2013 at 10:37:40 UTC, Artur Skawina wrote:
> On 07/24/13 12:09, monarch_dodra wrote:
>> Keeping it to "same type, 100% of the time" seems like the
>> best.
>
> No, it's a design bug. The head qualifier(s) should always be
> stripped
> when copying objects. Stripping is always fine (ie safe)
Nope. Stop. Wrong. Qualification is transitive in D, unlike in
C++. Even when copying, stripping qualification is not safe:
//----
struct S
{
int* p;
}
void main()
{
immutable i = 1;
auto a = immutable(S)(&i);
auto b = cast(S)a; //Unsafe cast
*b.p = 2; //This'll probably crash on a linux
//Program corrupted by here.
assert(i == *&i); //This fails (!!!) on my win32
}
//----
Long story short, never cast to Unqual. Always to an implicit
cast, and let the compiler complain if it is illegal:
//----
struct S1
{
int a;
}
struct S2
{
int* p;
}
void main()
{
immutable i = 1;
auto a1 = immutable(S1)(i);
auto a2 = immutable(S2)(&i);
S1 b1 = a1; //OK!
S2 b2 = a2; //Error: cannot implicitly convert expression
(a2) of type immutable(S2) to S2
}
//----
More information about the Digitalmars-d-learn
mailing list