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

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

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

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

Herb Sutter, Andrei Alexandrescu

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

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

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


Discussion


Once you go

const , you (should) never go back. If you cast away

const on an object whose original definition really did define it to be

const , all bets are off and you are in undefined behavior land. For example, compilers can (and do) put constant data into ROM or write-protected RAM pages. Casting away

const from such a truly

const object is a punishable lie, and often manifests as a memory fault.

Even when it doesn't crash your program, casting away

const is a broken promise and doesn't do what many expect. For example, this doesn't allocate a variable-sized array:

void Foolish( unsigned int n ) {
const unsigned int size = 1;

const_cast<unsigned int&>(size) = n;

// bad: don't do this
char buffer[size];

// will always have size 1

// …
}

C++ has one implicit

const_cast , the "conversion of death" from a string literal to

char* :

char* weird = "Trick or treat?";

The compiler performs a silent

const_cast from

const char[16] to

char* . This was allowed for compatibility with C APIs, but it's a hole in C++'s type system. String literals are ROM-able, and trying to modify the string is liable to cause a memory fault.


/ 521