tailieunhanh - HandBooks Professional Java-C-Scrip-SQL part 45

Tham khảo tài liệu 'handbooks professional java-c-scrip-sql part 45', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | polymorphic_cast Header boost Polymorphic conversions in C are performed via dynamic_cast. A feature of dynamic_cast which is sometimes also the cause of erroneous code is that it behaves differently depending on the type with which it is used. dynamic_cast tHRows an exceptionstd bad_castif the conversion is not possible when used on a reference type. The reason for the exception is simple. There is no such thing as a null reference in C so either the conversion succeeds and the result is a valid reference or it fails and you get an exception instead. Of course when using dynamic_cast to convert a pointer type failure is indicated by returning the null pointer. dynamic_cast s different behavior depending on whether pointer or reference types are used is a valuable property because it allows the programmer to express intent. Typically if a failed conversion doesn t constitute a logical error the pointer conversion is used and if it is an error the reference version is used. Unfortunately the difference is quite subtleit boils down to an asterisk or an ampersandand it isn t always a natural choice. What if a failed cast to a pointer type is an error To make that clear by having an exception thrown automatically and to make the code consistent Boost offers polymorphic_cast. It always throws a std bad_cast exception if the conversion fails. In The C Programming Language 3rd Edition Stroustrup has the following to say about dynamic_cast with pointer types and the fact that it can return the null pointer Explicit tests against 0 can beand therefore occasionally will beaccidentally omitted. If that worries you you can write a conversion function that throws an exception in case of failure. polymorphic_cast is precisely that conversion function. Usage polymorphic_cast is used just like dynamic_cast except pun intended that it always throws a std bad_cast on failure to convert. Another feature of polymorphic_cast is that it is a function and can be overloaded if .

TÀI LIỆU LIÊN QUAN
10    158    1
6    184    1
7    162    1
5    157    1
6    160    1
6    152    1
6    150    1
6    206    1
7    154    1