C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] - نسخه متنی

Herb Sutter, Andrei Alexandrescu

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


Discussion


Don't read a field of a

union unless it was the field that was last written. Reading a different field of a

union than the field that was last written has undefined behavior, and is even worse than doing a

reinterpret_cast (see Item 92); at least with the latter the compiler has the fighting chance to warn and repel an "impossible reinterpretation" such as pointer to

char . When abusing a

union , no reinterpretation of bits will ever yield a compile-time error or a reliable result.

Consider this code that is intended to deposit a value of one type (

char* ) and extract the bits of that value as a different type (

long ):

union {
long intValue_;
char* pointerValue_;
};
pointerValue_ = somePointer;
long int gotcha = intValue_;

This has two problems:

  • It assumes too much:
    It assumes that

    sizeof(long) and

    sizeof(char*) are equal, and that the bit representations are identical. These things are not true on all implementations (see Item 91).

  • It obscures your intent for both human readers and compilers:
    Playing

    union games makes it harder for compilers to catch genuine type errors, and for humans to spot logical errors, than even the infamous

    reinterpret_cast (see Item 92).



/ 521