Effective C + + reading notes (clause 18-23)

Source: Internet
Author: User

(iv). Design and declaration

_______________________________________________________________________________________________________________ _____________________

Article 18: Make the interface easy to use, but not easily misused

#1Importing new types can make interfaces difficult to misuse, and replacing objects with functions guarantees type safety.
For example:
Class date{Public:    Date (int month, Int. Day, int year);    ...} Add-on Type: Class Month{public:    static Month Jan () {return month (1);}    Static month Feb () {return month (2);}    ...    Static month Dec () {return month (n);}    .. private:    explicit Month (int m);    ...}; struct DAY{EXPLICIT Day (int d)    : Val (d) {}int val;}; struct year{explicit year (int y)    : Val (y) {}int val;};/ /You can call it this way: Date D (Month::mar (), Day (1995), and/or to ensure that type safety and interfaces are not easily misused.

#2What can be done in a restricted type, and what cannot be done can prevent customer errors.
For example, a const-decorated operator* return type prevents customers from making mistakes because of user-defined types.
if (a*b = c)  ... Oh, well, it's supposed to be a comparative action.


#3. " Ensure interface consistency "," Let types behavior and the behavior of the built-in types "can promote the interface is used correctly.


#4Any interface requires customers to remember to do something that is prone to "improper use".
For example, there are functions:
investment* createinvestment ();
and want to finally pass the investment* pointer to the name Getridofinvestment () function, the
Customer three times the chance to make a mistake: no pointer removed, no pointer removed multiple times, no pointer removed with getridofinvestment () function
We can change it to the following code:
Std::tr1::shared_ptr<investment> createinvestment () {    std::tr1::shared_ptr<investment> retVal ( Static_cast<investment*> (0),                    getridofinvestment);    RetVal = ...;   Another retVal points to the correct object    return retVal;}
This will prevent customers from making mistakes and avoid resource leaks.

#5The. Tr1::shared_ptr supports custom deleter, which can be used to guard against DLL problems and can be used to
Automatic release of the mutex (mutexes; see clause 14).
_______________________________________________________________________________________________________________ _____________________
Article 19: Design class like design type
#1How should the new type's objects be created and consumed?
#2What is the difference between the initialization of an object and the assignment of an object?
#3What does the new type mean if it is passed by value?
#4What is the "legal value" for the new type?
#5. Does your new type need to match an inheritance graph (inheritance graph)?
#6What kind of conversion does your new type need?
#7What kinds of operators and functions are reasonable for this new type?
#8What kind of standard function should be dismissed?
#9Who should take a member of the new type?
#10What is the "undeclared interface" of type (undeclared interface)?
#11How generalized is your new type?
_______________________________________________________________________________________________________________ _____________________
clause 20: Prefer to replace pass-by-value with Pass-by-reference-to-const
#1For custom types, replace Pass-by-value with Pass-by-reference-to-const as far as possible, before
are usually more efficient and can avoid cutting problems.
(Avoid the cost of constructors and destructors)

#2For built-in types, STL iterators and Function objects pass-by-value more appropriately.
(This part conforms to the C code, without the cost of the constructor, Pass-by-value is usually more than a pointer to implement
Reference is more efficient)

#3For small custom types, you should still use Passed-by-reference-to-const.
Reason 1:
Some compilers treat "built-in types" and "user-defined types" for small, inexpensive copy constructors
Different attitudes, even if they have the same underlying expression.
For example:
Some compilers refuse to put an object consisting only of a double into the buffer, but are happy to do so on a regular basis
Bare double to do so.
So it's better to use Passed-by-reference-to-const to pass than Passed-by-value.
Reason 2: As a user-defined type, its size can easily vary.
Reason 3: Using a different C + + compiler may change the size of the type, for example: In some standard library implementations
The string type is seven times times larger than other versions.
_______________________________________________________________________________________________________________ _____________________
clause 21: When you must return an object, don't be paranoid about returning it reference
#1Pointing to a local stack object with pointer or reference and returning it in the function will cause
Undefined behavior because the Locak stack object is destroyed when the function returns.
#2. return pointer or reference point to a local static and may require more than one such object
Causes multiple objects to point to an object at the same time, which is probably not the first you want.
For example:
Const rational& operator* (const rational& LHS, const rational& RHS) {    static Rational result;    result = ...;    return result;} BOOL operator== (const rational& LHS, const rational& RHS); Rational A, B, C, D;...if ((a*b) = = (B*d)) {//when the product is equal, do appropriate action;} else{//When the product is not equal, do the appropriate action;}
The result is always the statement block when equality is executed, because the same local static object is always returned,
This is not what we hoped for.
_______________________________________________________________________________________________________________ _____________________
article 22: Declaring a member variable as private
#1Remember to declare the member variable as private, which can give the customer
(1)The consistency of Access data (both through function access),
(2). Fine-grained access rights (no access, read-only access, write-only access, read-write access),
(3)Allow constraints to be guaranteed (by verifying the constraints of class with the function to notify other objects,
Verify the pre-and post-status of the function and perform synchronization control in a multithreaded state ... Wait a minute. )
(4)Add class encapsulation, and achieve resiliency (access control increases encapsulation; customer unified call,
But can change the internal behavior of the function increases the implementation of elasticity)
(5)Ensure that class constraints are always maintained, because only member functions can affect them.

#2The encapsulation of something is inversely proportional to the amount of code damage that can occur when its contents change.
(The so-called change may be to remove it from class (which may be advantageous for computational encapsulation))

#3. Protected is not more encapsulated than public.
reason: The public member variable is used by all customers who use it, and if it is removed, all use
Its client code will be destroyed, so the encapsulation is 0, and the protected member variable is all derived
Classes and the class itself, if removed, all the client code that uses it has been
Damage, so the encapsulation is also 0.
_______________________________________________________________________________________________________________ _____________________
clause 23: Ning to Non-member, Non-friend replace member function
#1If something is encapsulated, it degrades its visibility, and the more things are encapsulated, the fewer people can see it.
And the fewer people can see it, the greater the elasticity we have to change it, because our change affects only those
See the person or thing that changes.

#2.Rather take non-member, the Non-friend function replaces the member function. Doing so can increase
(1) Encapsulation:
Non-member, Non-friend function is less than member function to access internal protected members of class
and private members, in other words, less can be seen, so encapsulation is better.
(note, why not include the friend function here)

(2) package elasticity:
The encapsulation of the Non-member and Non-friend functions separates class from the function, reducing the number of code modifications
Compile dependencies, and therefore has a higher elasticity of the package. (To be more irrelevant to class)

(3) Expansion of function:
Non-member, non-friend functions can be placed in the same namespace as class, so
Can realize multiple groups of different source files in the convenience function, so as to achieve the separation of the expansion function.
(namespace can span multiple source files, but class does not)
For example:
-----------------------------------#include "WebBrowser.h" namespace Webbrowserstuff{class webbrowser{...}; ...//core functions, such as the Non-member function required by almost all customers}//-----------------------------------#include "WebBrowserBookmarks.h" Namespace webbrowserstuff{.//Bookmark-related convenience functions}//-----------------------------------#include "WebBrowserCookies.h" Namespace webbrowserstuff{...//cookies-related convenience functions}//-----------------------------------//If you want to add a set of convenience functions, you only need to include the relevant header file , it can be easily added in namespace//to realize the expansion function. <pre name= "code" class= "CPP" >//=============================================================// The following is an example of using the member function and the Non-member, Non-friend function://=============================================================  Class Webbrowser{public: ... void ClearCache (); Clear download element cache void ClearHistory (); Clears the visited URLs history void Removecookies (); Remove all cookies};//in the system if you want to implement the above three functions together, you can use the member () function, and the Non-member, non-friend function,//where the member () function is implemented in the following way: Class   Webbrowser{public: ... cleareverything (); Call Clearcache,clearhistory,removecookies function ...};//non-member, non-friend function implementation: void Cleareverything (webbrowser& wb) {Wb.clearcache ();    Wb.clearhistory (); Wb.removecookies ();}

_______________________________________________________________________________________________________________ _____________________


Effective C + + reading notes (clause 18-23)

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.