Effective C + + reading notes (clause 1-10)

Source: Internet
Author: User
Tags constant definition

Have to say, effective C + + is really a C + + advanced Good book, just browse through the second time,

It is now a summary of the general, and appropriate deployment, as a reference to the C + + review.


(a). Make yourself accustomed to C + +

_______________________________________________________________________________________________________________ _____________________

Article 1: Treat C + + as a language federal

#1. Divide C + + into four sub-languages: C,templete C + +, object-oritented C + +, STL;

_______________________________________________________________________________________________________________ _____________________

clause 2: Try to replace #define with const, enum, inline
#1. Replace # define with a const.
Reason 1: The preprocessor removes the token name, causing the token name not to enter the symbol table, and when a compilation error occurs, you can only get the defined value, so you don't know where the error came from.
Reason 2: The preprocessor blindly replaces the token name with a defined value, which causes the target code to have multiple defined values, which increases the target code.

Reason 3: #defines不能用来定义class专属常量, while Const can.

#2. Use enum instead of # define
reason: #define对其后的编译过程都有效, and if you want to restrict scope to a class, use
Constants that are determined before compilation can use the static const int or "The enum hack", such as enum{num=5;},
But in some ways the enum is closer to # define behavior, such as enum and define cannot fetch addresses,

The const can take the address, which avoids pointer and reference pointing to a constant in your enum to implement the constraint.

#3. Replace # define with inline
such as: #define CALL_WITH_MAX (a) f (a) > (b) ( A):(B))
Use Call_with_max (++a, b);//a will be accumulated two times

Swapping with the inline function gives you the efficiency of this macro and executes correctly.

_______________________________________________________________________________________________________________ _____________________

Clause 3: Use const as much as possible because this identifier tells the compiler to add constraints
#1. bitwise constness is a constant definition of C + +, the compiler follows this rule, but sometimes for performance, you can consider the logical constants, skillfully use mutable to realize the function that the client cannot detect.
#2To avoid const and non-const overloaded function code duplication, you can use Non-const to invoke const in the transformation, and vice versa, because the const function's intent is not to allow changes, do not break the rule.

_______________________________________________________________________________________________________________ _____________________

Article 4: Determine that the object was initialized before it was used
#1The default constructor initialization action occurs before entering the constructor body to ensure efficient performance,
For a custom type, initialize in the member's initial column instead of assigning a value in the constructor body.
#2For built-in data types, to avoid ambiguous behavior and the consistency of member initialization, it is best to
Initialization in the initial column
#3If you have more than one constructor and initialize multiple built-in data types, to avoid repetitive actions, you can
Initializes the assignment behavior to the function and calls the function at the same time.
#4To exempt the cross-compilation unit initialization order issue, replace the non-local static object with the local static object.
Reason 1: Non-local static object is initialized by a non-local static object in another compilation unit.
Because the compilation unit order is ambiguous, the former is not guaranteed to be initialized.

Reason 2: The local static object is initialized when it first encounters a function call, so there is no initialization cost when not in use.

_______________________________________________________________________________________________________________ _____________________


(b). Construction/Destruction/assignment operations

_______________________________________________________________________________________________________________ _____________________

Article 5: Understand what functions the C + + compiler silently writes and calls
#1The compiler secretly created a default constructor for class, a copy constructor, a copy assignment operator, and a destructor.
#2If class contains a const or reference member variable, the result of calling the default copy assignment is
The compiler refuses to compile the line unless you define the copy assignment yourself.
#3If base classes declares the copy assignment operator as private, the compiler rejects the

Derived class generates a copy assignment operator.

_______________________________________________________________________________________________________________ _____________________

Article 6: In order to dismiss the compiler to automatically generate the function, the member function can be displayed declaration private, and do not implement
For example:
Class Homeforsale{public: Private:homeforsale (const homeforsale&); Homeforsale operator= (const homeforsale&);}
Private means that when attempting to copy a Homeforsale object, it is rejected by the compiler, if inadvertently
Called by the member function or friend function and is complained by the linker because it does not provide implementation.

If you want to transfer link-period errors to the compilation period, you can use inheritance, such as
Class Myhomeforsale:private homeforsale{...};
When you try to generate the copy constructor and the copy assignment operator, the base class is called

The function version failed and was rejected by the compiler.

_______________________________________________________________________________________________________________ _____________________

Article 7: Declaring a virtual destructor for a polymorphic base class
#1The base classes with polymorphic properties should declare a virtual destructor, with no polymorphic base classes
The virtual destructor should not be declared, and Non-base class should not declare the virtual destructor (virtual increases the object volume space).
(with polymorphic nature means that there may be a base-class pointer pointing to a derived class object)

#2. The virtual function in class implies a polymorphic nature, so it is also necessary to have a virtual destructor.

_______________________________________________________________________________________________________________ _____________________

Article 8: Don't let exceptions escape destructors
#1In the case of two exceptions, a program that is not finished is a result of ambiguous behavior.
#2. Do not let the destructor spit out the exception, if a function called by the destructor may throw an exception, the destructor
The function should catch any exceptions, and then they (do not propagate), or end the program, otherwise easily lead to ambiguous behavior.
#3A better strategy is to write a common function for the client to call, and then give the client an opportunity to catch the exception,
In the destructor, the normal function is executed, and the function exception is caught when it needs to be executed, and the principle of # # is realized.
Such as:
Class Dbconn{public: ... void close () {    db.close ();    bclosed = true;} ~dbconn{    if (!bclosed)    {        try{            db.close ();            Bclosed = true;        } catch (...)        {        //make a running record, note that the call to close failed ...        }}}    Private:dbconnection DB; BOOL bclosed;}

_______________________________________________________________________________________________________________ _____________________

Article 9: Never call the virtual function in a construct or destructor
#1. Make sure that none of your constructors and destructors call the virtual function (during object creation and destruction),
All of the functions they invoke are also subject to uniform constraints.
Reason 1: The derived class exclusive member was not initialized during the derived class object base class construct.
Calling derived class's function results in ambiguous behavior, so this is just a call to the corresponding function of base class.
There is no real meaning to virtual. (The same as the destructor)
Reason 2: During the base class construction of the derived class object, the object type is base class and not derived
Class, so the virtual function is parsed to the base class by the compiler. In addition, the run-time type information dynamic_cast and
The same is true of typeid. (The same as the destructor)
Reason 3: Because of the above reasons, when the virtual function is called in a constructor or destructor, some compilers
Issue a warning message.

#2To address these issues, you can use the static function of the derived class to pass information to the base class constructor or destructor technique.
Such as:
Class Transaction{public:    explicit Transaction (const std:string& loginfo);    void Logtransaction (const std:string&loginfo) const;    ...}; Transaction::transaction (const std::string& loginfo) {    ...    Logtransaction (loginfo);} Class Buytransaction:public Transaction{public:    buytransaction (parameters);    : Transaction (createlogstring (parameters)) {...}    ... private:    static std::string createlogstring (parameters);};

_______________________________________________________________________________________________________________ _____________________

clause 10: Make opertator= (+=,-=,*= similar operator) return a reference to *this
Reason 1: Reference has better performance than assignment in custom types.
Reason 2: This protocol is provided by all built-in types and standard library types, such as String,vector,complex,

Tr1:shared_ptr and so on, for the sake of unification, or abide by it!

_______________________________________________________________________________________________________________ _____________________


Effective C + + reading notes (clause 1-10)

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.