Specification
- Template and generic programing not marked(40-47)
- Design and implememt need more code experience to understand
- Effective c++ need read more than one times
- Learning by code
Item1 default constructor:
called with no arguments
has no parameter or default value for every parameter.
default constructer should be ‘explicit’ to avoid ‘implicit type conversion’
‘copy instructor’:initialize an object with a different objrect of the same type.
‘copy assignment operator’: copy the value from one object to another of the same type.
‘object passed by value’ in the way of ‘copy construtor’
Rules for effective c++ programming vary,depending on the part of c++ you are using :C OOP Template STL
Item2 Prefer const ,enum,and inline to #define
const not many copy like #define and can be private.
enum can be referenced but #define cann`t
For simple constants ,prefer const objects to #define
For function-like macros, prefer inline function to #define.
Item3 Use const whenever possible
whenever it`s true ,to do so -const.
for pointer ,you can specify whether the pointer itself is const ,the data it point to is const,both or neither.
12345678 char *p = greeting;// non-const pointer,// non-const dataconst char *p = greeting;// non-const pointer,// const datachar * const p = greeting;// const pointer,// non-const dataconst char * const p = greeting;// const pointer,// const datafor iterator , const iterator is the iterator itself is const , but const_iterator , the object it point to ia const
const member function make it possible to work with const object.
return in c++ is return a copy of the parameter not itself,which invoked a copy constructor
Declaring something const helps complier
detect usage errors and can be applied to objects at any scope.
$ compiler enforce bitwise constness but you should program using logical constness.
$ when const and non-const member function have essentialy identical implementions, code duplication can be avoided by having the non-const version call the const version.
Item4 Make sure object initialized before used
make sure that all construtors initialize everything in ht eobject.
data members that are const or are reference must be initialzied and can not be assignment.
construtor Destructor and assignmentOperation
Item5: know what function c++ silently writes and calls
Item6: Explicitly disallow the use of compiler-generated functions you do not want.
make the function you don`t want be private in the base class.
To disallow functionality provided by cpmlilers, declare the corresponding member function ‘private’ and give no imlementations.
Item7: Declare destructors virtual in plomorphic base classes.
Give the base class a virtual destructor then deleting a derived class object will do exactly what you want.
a class not intended to be a base class should not have a virtual funtion.
Item8: Prevent exception from leaving destructors
- Destructors should never emit exceptions. if functions called in a destructor may throw,the destructor should catch ant exceptions, then swallow them ot terminate the program.
- if a class clients need to be able to react to exceptions thrown during an operation, the class should provide a regular function that performs the operation.
Item9 :Never call virtual function during constructor or destructor
Item10: Have assignment operators return a reference to *this
‘x=y=z=15, thus x=15,y=15,z=15’
the way is implemented is that assignment returns a reference to its left-hand arguement.
|
|
Item11: Handle assignment to self in operator=
|
|
if the ‘new’ failed, pb will pointer to an undefined address.
namespace std
{
template
void swap(T& a, T& b)
{
T temp(a);
a = b;
b = temp;
}
}
- swap in pointer the type must support copy constructor and copy assignment1Not swap the object itself which is so ineffcient,but swap the pointer.
template<>
void swap
{
swap(a.pImpl, b.pImpl);
}
- When you want to “partially specialize” a function template, the usual approach is to simply add an overload
Implementions
Item26: Positive varible definitions as long as possible
for variable to use in a loop ,define it out of the loop may be more effecient
Item27 Minimize casting
c++ style casting
const_cast
( expression ): cast const object to non-object
dynamic_cast( expression ): safe downcasting
reinterpret_cast( expression )
static_cast( expression ): implicit concersion
✦ Avoid casts whenever practical, especially dynamic_cast s in performance-sensitive code. If a design requires casting, try to develop a cast-free alternative.
✦ When casting is necessary, try to hide it inside a function. Clients can then call the function instead of putting casts in their own code.
✦ Prefer C++-style casts to old-style casts. They are easier to see, and they are more specific about what they do.
Item28 Avoid returning “handles” to object internals
Item29 Strive for exception-safe code $$
Exception-safe functions leak no resources and allow no data structures to become corrupted, even when exceptions are thrown. Such functions offer the basic, strong, or nothrow guarantees.
✦ The strong guarantee can often be implemented via copy-and- swap ,but the strong guarantee is not practical for all functions.
✦ A function can usually offer a guarantee no stronger than the weakest guarantee of the functions it calls.
Item30 Understand the ins and outs of inlineing $$
inline in most c++ programs ia a compile-time activity.
inline functions typically be in header files
limit most inlineing to small as possible
Dont`t declare function template inlne just because they appear in header files
Item31 MInimize complication dependence between files
- Avoid using objects when object reference and pointer will do
- Depend on class declaraton instead of class definitions whenever you can
- Provide aeperate header files for declarations and definition
Inheritence and object-oriented design
Item32 Make sure public ingeritence model “is a”
Everythings that applies to base class must also apply to the derived class ,because every derived class object is a base class object.
Item 33 Avoid hiding inheriented names.
the scope of a derived class is nested inside its base class`s scope.
the same name member funtion in derived class will hide the member funtion with the same name inthe base class ,even if the parameter is different, regaedless of whether the funtions are virtual or non-virtual.
- if you use pubic inheritence ,you can`t inherit the overloads.
pubic derived allow to override c+ + `s default hiding of inherited names
*using base:: functionname;
make all things in base named functionname visible in derived class, andd the c++ scope search will find the most appropriate member funtion between tha base class function and derived class member function with the same name
Things to Remember
- Names in derived classes hide names in base classes. Under public inheritance, this is never desirable.
- To make hidden names visible again, employ using declarations or forwarding functions.**
item34 Differentiate betwwen inhertance of interface and inheritance of impletention
- derived class inherit only the interface(declaration):
interface only
- derived class inherit both the inteface and the implement, but may be overrided the implemention:
interface and a default implementation
- derived class inherit both the inteface and the implement, but without override anything:
inteface and a mandatory implementation
- pure virtual function
$ must be redeclared in any derived class
$ derived class inherit a function interface only. - simple virtual function
$ derived class inherit the interface
$ the implementation derived can be overrided
$ if it`s not overrided , call the default implementation in the base class - non-virtual function
$ inteface and a mandatory implementationMember function interface are always inherited
Item35 Consider alternatives to virtual functions.
- Design Pattern : Template Method call private virtual function through public non-virtual member functions ‘??’
The Strategy Pattern via Function Pointers
The Strategy Pattern via tr1::function
The “Classic” Strategy Pattern
- Use the non-virtual interface idiom (NVI idiom), a form of the Template Method design pattern that wraps public non-virtual member functions around less accessible virtual functions.
- Replace virtual functions with function pointer data members, a stripped-down manifestation of the Strategy design pattern.
- Replace virtual functions with tr1::function data members, thus allowing use of any callable entity with a signature compatible with what you need. This, too, is a form of the Strategy design pattern.
- Replace virtual functions in one hierarchy with virtual functions in another hierarchy. This is the conventional implementation of the Strategy design pattern.
Item36 Never redifine an inherited non_virtual function
non-virtual function is statically bound, but virtual funtion are dynamically bound
refifine a non-virtual function will make the compiler exhaust.
Item37 Never redefine a function’s inherited default parameter value
virtual function are dynamically bound, but default parameter values are statically bound
all the derived function will inherit the defualt parameter.
Item38 Model “has a” or “is-implemented -in-terms-of”through composition $
- Composition has meanings completely different from that of public inheritance.
- In the application domain, composition means has-a. In the implementation domain, it means is-implemented-in-terms-of.
Item 39 Uasage private inheritance judiciously $$
- can not convert a derived class object into abase class object if the inheritence relationship id private
- members inheriente from the base class will be private member of the derived class.
private inheritance means only software implementation
- Private inheritance means is-implemented-in-terms of. It’s usually inferior to composition, but it makes sense when a derived class needs access to protected base class members or needs to redefine inherited virtual functions.
- Unlike composition, private inheritance can enable the empty base optimization. This can be important for library developers who strive to minimize object sizes.
####Item 40 Uasage multiple inheritance judiciously $$
- Multiple inheritance is more complex than single inheritance. It can lead to new ambiguity issues and to the need for virtual inheritance.
- Virtual inheritance imposes costs in size, speed, and complexity of initialization and assignment. It’s most practical when virtual base classes have no data.
- Multiple inheritance does have legitimate uses. One scenario involves combining public inheritance from an Interface class with private inheritance from a class that helps with implementation.
Templates and Generic Programming $$
Item41 Understand implicit interfaces and compile-time polymorphism.
- Both classes and templates support interfaces and polymorphism.
- For classes, interfaces are explicit and centered on function signatures. Polymorphism occurs at runtime through virtual functions.
- For template parameters, interfaces are implicit and based on valid expressions. Polymorphism occurs during compilation through template instantiation and function overloading resolution.
Item 42: Understand the two meanings of typename.
The general rule is simple: anytime you refer to a nested dependent type name in a template, you must immediately precede it by the word typename .
- When declaring template parameters, class and typename are interchangeable.
- Use typename to identify nested dependent type names, except in base class lists or as a base class identifier in a member initialization list.