Effective C + + learning notes

Source: Internet
Author: User

--------------------1 make yourself accustomed to C + +-----------------------------------------

Rule 1: think of C + + as a language federation with 4 sub-languages:C(chunks, statements, preprocessor, built-in data types, arrays, pointers); object-oriented C + +(class, encapsulation, inheritance, Polymorphic, virtual functions); templates C + +;STL(containers, iterators, algorithms, and function objects). Don't be surprised when you switch from one language to another, leading to an efficient programming code that requires you to change your strategy.

Rule 2: Try replacing the #define with const,enum,and inline as much aspossible with the compiler instead of the preprocessor.

Rule 3: use const whenever possible . the most powerful application of const is the application of function declaration: function return value, parameters, member function itself.

Rule 4: Determines that the object was initialized before it was used. There are three issues to be concerned with:1. anything else unexpected to the built-in type ensures that each constructor initializes each member of the object. 2. The constructor's initial value column lists the member variables in the same order as they are declared in class . 3. The initialization order of non-local static objects that are defined in different compilation units is undefined. Workaround: Move each non-local static object into its own exclusive function (the object is declared as static within this function )

-------------------2 structure / destructor / assignment Operation ----------------------------------------

Rule 5: Understand that C + + silently writes and calls these functions (both public and inline): default constructor, default destructor, copy constructor, copy assignment operator function.

Rule 6: Explicitly deny if you do not want to use a function that is automatically generated by the compiler. For example, if you do not want the class to be copied or assigned, you should explicitly reject it, there are two methods.

Rule 7: Declares the virtual destructor for the polymorphic base class .

Rule 8: Let the exception escape the destructor. Destructors should never spit out exceptions, which can lead to premature end of programs or ambiguous behavior. If a function called by a destructor might throw an exception, the destructor should catch any exceptions and then swallow them (not propagate) or end the program.

Rule 9: Never call virtual functions during construction and destruction, such calls never descend to derived classes. The workaround is to enable the derived class to pass the necessary construction information up to the base class constructor. If the function is static, it is not possible to accidentally point to a member variable that has not been initialized within the initial immature object .

Rule: Make operator = return a referenceto *this.

Rule one: " self-assignment " is handled in operator =.

Rule: Do notforget every ingredient when copying objects.

---------------------3 Resource Management ---------------------------------------------------------

Rule: Manage resources with objects. Make resources available during construction and released during destruction.

Rule: Carefully copying behavior in the resource management class . When a RAII object is copied, there are 2 ways to handle it:1. prohibit copying, 2. The " reference Counting" method is used for the underlying resource : Typically, if a tr1:shared_ptr member variableis included, the raiiclasses can implement the copy behavior of the reference count.

Rule: Provides access to the original resource in the resource management class.

Rule: Use the same form when using new and delete in pairs .

Rule: Place the Newed object in a smart pointerwith a stand-alone statement , which could lead to a resource leak, the following statement should be:

Processwidget (std::tr1::shared_prt<widget> (Newwidget), priority ());

Replace with (stand-alone statement)

STD::TR1::SHARED_PTR<WIDGET>PW (new Widget);

Processwidget (Pw,priority ());

----------------------------4 Design and declaration -------------------------------------------------------

Rule: Make the interface easy to use correctly, not easy to be misunderstood.

Rule: Design class is like design type. It should be as cautious as the language designer originally designed the language built-in type to discuss class design.

Rule: Try to replace pass-by-value with Pass-by-reference-to-const, but Pass-by-value is often appropriatefor built-in types .

Rule: When you must return an object, don't be paranoid about returning its reference.

Rule: Declare the member variable as private.

Rule: Rather , replace the member function with Non-memberandnon-friend .

Rule: If a type conversion isrequired for all parameters of a function, including the metaphor parameter referred to by this pointer, then that function must be a non-member.

Rule: Consider writing a swap function that does not throw an exception .

----------------------------------------5 Implementation ------------------------------------------------------

Rule: Defer the occurrence of variable definitions as much as possible, thus avoiding the need to construct ( and refactor ) non-essential objects.

Rule: Try to be less transformational. Centralized transformation type for C + +:

const_cast<t> (expression)// The only thing that can be used to remove the constants of an object.

dynamic_cast<t> (expression)// Security down transition

reinterpret_case<t> (expression)// perform low-level transformation

static_cast<t> (expression)// forcing implicit conversions, such as non-const objects to const objects, or converting int to Double , and so on.

Rule: Avoid returning handles points to the inner component of the object, which destroys encapsulation and const .

should be

point& Upperleft () const {RETURNPDATA->ULHC;}

Replaced by

Const point& Upperleft () const {RETURNPDATA->ULHC;}

Rule: try to make it worthwhile for " exceptional security " .

Rule: A thorough understanding of inlining. Do not declare any functions as inline at first, or at least limit the scope of inlining execution to those " must be inline" or " very bland " on the function body.

Rule: Minimizes compilation dependencies between files and separates interfaces from implementations. The general idea is to be dependent on the declarative, not dependent on the definition of the formula. The 2 instruments based on this conception are handle classes and interface classes.

--------------------------6 inheritance and object-oriented design ---------------------------------

Rule: Make sure your public continues to mold out the is-a relationship.

three kinds of relationships between classes:is-a,has-a,is-implemented-in-terms-of(according to something)

Rule: Avoid hiding the inherited name.

If you inherit base class and add overloaded functions, and you want to redefine or overwrite some of them, you must introduce a using declaration for each name that would otherwise be obscured , or the name you wish to inherit will be obscured.

when you do not want to inherit all the functions of base class, you can use private inheritance and handoff functions (what is a handoff function?). function that calls the base class function).

Rule: Distinguishes between interface inheritance and implementation inheritance.

Rule: Consider alternatives other than the virtual function.

Implement template method mode by Non-vitualinterface : Virtual functions should be almost always private, so that customers The Non-virtual member function calls the private virtual function indirectly.

The policy mode is implemented by a function pointer.

Rule: Never redefine the inherited non-virtual function.

Rule PNS: Never redefine inherited default (default) parameter values.

Rule: By compounding the mold out of the has-a or " according to the realization of something ."

Rule: Use private inheritance wisely and prudently . If class D inherits class B as private, it is intended to use some of the features already in the ClassB.

Rule: Use multiple inheritance wisely and prudently.

-----------------------7 templates with generic programming -------------------------------------------------------------------

Rule: Understand implicit interfaces and compile-time polymorphism.

Both classes and templates support interfaces and polymorphism.

for classes , the interface is explicit, centered on the function signature, and polymorphic through the virtual function at run time.

for the template parameter, the interface is implicit, based on a valid expression (such as an expression within an if statement), polymorphism is through template with the initialization and function overload resolution occurs at compile time.

Rule: Understand the dual meaning of TypeName.

Rule: Learn how to obtain a name from a base class template.

Rule: The parameter-independent code is extracted from the templates.

Rule: Use the member function template to accept all compatible types.

Rule: Define a non-member function for the template when a type conversion is required.

Rule: Please use the traitsclasses expression type information.

Rule: Recognize templates meta programming.

------------------------8 customizing new and Delete------------------------------------------------------------------------

Rule: Understand the behavior of New-handler.

Rule: Learn The appropriate replacement time for new and delete.

Rule: You need to stick to the routine when writing new and delete .

Rule: Write placementnew also write placement delete.

------------------------------------9 Miscellaneous Discussions ------------------------------------------------------------ ----------------

Rule: Don't overlook compiler warnings.

Rule: Familiarize yourself with the standard library of programs, including TR1.

Rule: Make yourself familiar with boost.


This article is from "Firekido's Technical Life" blog, please make sure to keep this source http://zhangzhao.blog.51cto.com/12934593/1970517

Effective C + + learning notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.