Announcements and Reminders
|
Recording Comments on Assignment 1Common mistakes
Word::Word(const char* text) Loose EndsRvalue referencesRvalue references permits a reference to bind to a rvalue – a temporary or a literal. This is useful for the move constructor or the move assignment operator, avoiding the expense of copying an object for this purpose.Move Semantics With
the use of rvalue references in C++11, the move constructor and the
move assignment operator was added as a replacement for the copy
constructor and the overloaded assignment operator.
Example 2-4 – Move Semantics typedef and usingThe keyword, typedef,
originally from C, is used to define a type.
C++ 11 introduced the keyword, using to act like typedef. typeid operatorThe
typeid operator returns an identifier of a type, a variable or an
expression. The return of the typeid is a class type, called
type_info. You can use the name() member function of the
type_info class to display a literal description of the type. Example 1-8 – typedef, using, typeid The generic size functionThe
generic size function was introduced in C++17. It returns the
size of an array (number of elements) or the size of a C++ container;
Example 2-6 - The size function C++ Cast OperatorsStatic CastA
static_cast is used to convert one type to another.
Generally,
static_casts should not be used and may be considered
dangerous.
Often, conversions are automatic and the need to use a static_cast may
imply that incorrect types are in use. Static_cast are often
used
to convert one pointer type to another, or to convert an enumerated
value to an integer value.
Example 4-1 – static_cast Const CastA
const_cast is used to add or remove constness to an
expression.
Note, removing constness from a “pointed to” value may result in
undefined behavior.
Example 4-2 – const_cast Reinterpret CastA
reinterpret_cast is used to cast one type to another. It is
most
commonly used to treat one pointer type as another pointer type, or to
treat a pointer type as an integer type and vice versa. Note,
this case type may be unsafe and to use it effectively, the sizes of
the casted value and the casted type should match.
Example 4-3 – reinterpret_cast Dynamic Cast
A
dynamic_cast is used with inheritance to cast a base class pointer or
reference to a derived class pointer or references. This is
called downcasting. In order for this to succeed, the base
class
must be polymorphic (contains a virtual function).
Reference: http://www.bogotobogo.com/cplusplus/upcasting_downcasting.php Example 4-4 – dynamic_cast |