开发者

Explicit type conversion

I have read in a book that specifies this :

//: C03:SimpleCast.cpp
int main() {
int b = 200;
unsigned long a = (unsigned long int)b;
} ///:~

"Casting is powerful, but it can cause headaches because in some situations it forces the compiler to treat data as if it were (for instance) larger than it really is, so it will occupy more space in memory; this can trample over other data. This usually occurs when casting pointers, not when maki开发者_JAVA百科ng simple casts like the one shown above."

Now can You please provide an example where casting pointer can trample other data?


int main(void)
{
    short int a = 5;
    short int b = 7;
    *(long int*)&a = 0;
}

Assuming sizeof(long) > sizeof(short), and assuming the compiler puts a on the stack before b, b will be trashed.


int main() { 
    char a[] = "This is a string.";

    *(long *)a = 12345678;  // will typically overwrite first four or eight bytes of a.

    std::cout << a;
    return 0;
}


char unix[5]="unix";
char* first= &(unix[0]);
int * intptr= (int*) first;
*first=64;
printf("%s\n",unix); /* prints @ /*


Since this was tagged as C++, not C, I also recommend reading up on C++ style casts over C style casts:

static_cast<Derived *>(pBase)->DMethod();
if (dynamic_cast<Derived *>(pBase)) dynamic_cast<Derived *>(pBase)->DMethod();
const_cast<CRect &>(constRect).x = 3;
int *pInt = reinterpret_cast<int *>(charbuff);

I highly recommend Scott Myer's book Effective C++, 55 Specific Ways to Improve Your Programs and Designs, 3rd Edition that explains these very well. Make sure you get the 3rd Edition, although the 2nd Edition may also have covered C++ style casts too.

Basically, if you are using C++ and your compiler was written within the last 10 years, NEVER use C-style casts. Use C++ style casts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜