(Objective C ++) Chapter 1 habits C ++ (view yourself to C ++)

Source: Internet
Author: User
Tags define function
1.1 Clause 1: view C ++ as a federated Language)

Main sub-language (sublanguage) of C ++ ):
L [3-1-1] C ++ is still based on C. Block (blocks), statement (statements), Preprocessor (preproccessor), built-in data type (built-in data types), array (arrays), pointer (pointers) and so on.
L [3-1-2] object-oriented C ++. Class classes, encapsulation (encapsulation), inheritance (inheritance), polymorphism (polymorphism), virtual functions (dynamic binding), and so on
L [3-1-3] template C ++ is the generic programming (genericprogramming) part, which brings a brand new programming model (programming paradigm), the so-called template metaprogramming (TMP, template metaprogramming ).
L [3-1-4] STL is a template library. It applies to containers, iterators, algorithms, and function objects ).

1.2 Clause 2: Use consts, enums, and inlines whenever possible. Use less # define (prefer consts, enums and inlines to # define)

In the C ++ program, try to use consts, enums, and inlines, and use less # define.
L [3-2-1] For constants, it is best to replace # defines with a const object or enum.
L [3-2-1] for macro (macros) Like a function, it is best to use the inline function instead.

For example:
Constdouble Pai = 3.1415;
Const char * const Hello = "hello ";
Const STD: String author_name = "wuzhenghua ";
Class canimal
{
PRIVATE:
Const int color = 1;
};
Example 3-2-1 constant

We cannot use macro # define to create a class-specific constant, because # define does not focus on scope ).
An enumerated value can be used as an ints value. The enumeration behavior is like # define, not Const. For example, a const address is valid, but an Enum address is invalid, and the # Define address is invalid.
# Define function 1 is the Ambiguity Caused by statements, and 2 is the absence of security type check. Therefore, it is best to use the inline function as follows:

Template <typename T>
Inline void max (const T & A, const T & B)
{
F (A> B? A: B );
}
Example 3-2-2 Inline Function

1.3 Clause 3: Use const (use const wheneverpossible) whenever possible)

One amazing thing about const is that it allows you to specify a semantic constraint (that is, to specify an object "not modified"), and the compiler enforces this constraint.

1.3.1 const and pointer

Face the pointer, modify the pointer, or modify the pointer. If the key value const appears on the left side of the asterisk, it indicates that the indicated object is a constant. If it appears on the right side of the asterisk, it indicates that the pointer itself is a constant. If it appears on both sides of the asterisk, both are constants.

Char greeting [] = "hello ";
Char * P = greeting; // non-const pointer, non-const data
Const char * P = greeting; // non-const pointer, nconst data
Char * const P = greeting; // const pointer, non-const data
Const char * const P = greeting; // const pointer, const data
Example 3-3-1 const and pointer variable

1.3.2 const and iterator

If you want the iterator to indicate something that cannot be modified (that is, you want STL to simulate a const T * pointer), you must use const_iterator:
STD: vector <int> VEC;
Const STD: vector <int >:: iterator iter = VEC. Begin (); // ITER image T * const
* Iter = 10; // correct
ITER ++; // Error
STD: vector <int >:: const_iterator citer = VEC. Begin (); // ITER like const T *
* Citer = 10; // Error
Citer ++; // correct
Example 3-3-2 const and iterator

Making the function return a constant value can reduce accidents caused by customer errors, rather than giving up security and efficiency.
Class rational {...};
Const rational operator * (const rational & LHS, const rational & RHs );
Rational A, B, C; // correct
If (A * B = C) // In fact, if you want to make a comparison and drop a =, the compiler reports an error.
Example 3-3-3 const and operator *

1.3.3 const and member functions

Reasons: First, const is a class interface that is easy to understand; second, const makes "operate on const objects" possible. If the two member functions are different in constness, they can be overloaded. This is an important feature of C ++. The const member function cannot change any non-static member variables in the object.

Const and non-const member functions should avoid code duplication.
Class textblock {
Public:
...
Const char & operator [] (STD: size_t POS) const
{
...
}
Char & operator [] (STD: size_t POS)
{
Return const_cast <char &> // remove the const returned by OP []
(Static_cast <const textblock &> (* This) // Add const to * This
[POS];
}
...
}
Example 3-3-4 const and member functions

[Note] the non-const member function can perform any action on its object. Therefore, calling a const member function does not pose any risk.

1.4 Clause 4: C ++ seems capricious about "initializing objects" (make sure that object areinitialized before they're used)

C ++ seems capricious about initializing objects.
Make sure that each constructor initializes every member of the object. However, do not confuse assignment and initialization ).
Class abentry {
Public:
Abentry (const STD: string & name, const STD: List <phonenuber> & phones );
PRIVATE:
STD: String thename;
STD: List <phonenuber> thephones;
Int numtimesconsulted;
}
Abentry (const STD: string & name, const STD: List <phonenuber> & phones ){// Values are assigned.
Thename = Name;
Thephones = phones;
Numtimesconsulted = 0;
}
Abentry (const STD: string & name, const STD: List <phonenuber> & phones): thename (name), thephones (Phones), numtimesconsulted (0)
{// Initialization

}
Example 3-4-1 assignment and initialization

C ++ specifies that the initialization action of the object's member variables takes place before entering the constructor ontology. The member initialization column (memberinitialization list) is more efficient than the value assignment, but the built-in type efficiency is the same.

Once you have carefully initialized the "Internal member variables", and make sure that your constructor uses the "Initial member column" to initialize base class and member variables, then there is only the initialization order of the non-conststatic object defined in different compilation units.

The so-called static object has a life cycle from being constructed until the end of the program. Such objects include global objects, objects defined in the namespace scope, objects declared static within the class, within the function, and within the file scope.

The static objects in the function are called local static objects, and others are called non-local static objects.

The so-called translationunit refers to the source code that generates a single object file.

C ++ does not clearly define the initialization sequence of non-local static objects defined in different compilation units.

To solve this problem, move each non-localstatic object to its own exclusive function (this object is declared as static in this function ). These functions return a reference pointing to the objects it contains. Then, the user calls these functions without directly involving these objects.

C ++ ensures that the local static object in the function will be initialized when "this function is called" and "the definition of this object is first met.

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.