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

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

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

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

Herb Sutter, Andrei Alexandrescu

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

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

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


Discussion


Consider replacing uses of

static_cast with its more powerful relative

dynamic_cast , and then you won't have to remember when

static_cast is safe and when it's dangerous. Although

dynamic_cast can be slightly less efficient, it also detects illegal casting (and don't forget Item 8). Using

static_cast instead of

dynamic_cast is like eliminating the stairs night-light, risking a broken leg to save 90 cents a year.

Prefer to design away downcasting: Refactor or redesign your code so that it isn't needed. If you see that you are passing a

Base to a function that really needs a

Derived to do its work, examine the chain of calls to identify where the needed type information was lost; often, changing a couple of prototypes leads to an excellent solution that also clarifies the type information flow to you.

Excessive downcasts might indicate that the base class interface is too sparse. This can lead to designs that define more functionality in derived classes, and then downcast every time the extended interface is needed. The one good solution is to redesign the base interface to provide more functionality.

If, and only if, the overhead of the

dynamic_cast actually matters (see Item 8), consider defining your own cast that uses

dynamic_cast during debugging and

static_cast in the "all speed no guarantees" mode (see [Stroustrup00]):

template<class To, class From>

To checked_cast( From* from ) {
assert( dynamic_cast<To>(from) == static_cast<To>(from) && "checked_cast failed" );
return static_cast<To>( from );
}
template<class To, class From>

To checked_cast( From& from ) {
assert( dynamic_cast<To>(from) == static_cast<To>(from) && "checked_cast failed" );
return static_cast<To>( from );
}

This little duo of functions (one each needed for pointers and references) simply tests whether the two casts agree. We leave it up to you to customize

checked_cast for your needs, or to use one provided by a library.


/ 521