"Effective C + +" Reading notes (ii)

Source: Internet
Author: User
Tags shallow copy

I. Resource management

Resource management is our application of resources, whether it is memory, mutexes, files, etc., after use, all need to return to the system. C + + does not have its own garbage collection mechanism, so it is very important to grasp the management of resources!

13. Managing Resources with objects:

A) Place all the resources required by an object inside the object, allocate resources when the object is initialized, and release the resource when the object is destroyed.

b) We usually new an object and then point to the object through the pointer and delete it after use. But sometimes the delete is forgotten, or the function return before the delete, when the pointer is gone, the object's memory space is leaked. For this scenario, you can use Auto_ptr to resolve.

c) atuo_ptr, smart pointer. When Auto_ptr is destroyed, the content that auto_ptr points to is automatically released. In other words, the content that the auto_ptr pointer points to does not require us to delete, and when the function scope is exceeded, the auto_ptr automatically destroys and the object it refers to is destroyed directly. However, the nature of AUTO_PTR determines its other characteristics, if the auto_ptr copy or assign value, the original auto_ptr will be empty.

D) is better than auto_ptr for shared_ptr, and auto_ptr usage is the same, but shared_ptr has a reference counting mechanism that cleans up resources when the reference count is 0.

e) Auto_ptr mechanism compared to the egg pain, so commonly used or shared_ptr. Note that both do delete, not delete[] operations, so pointing to an object is an object, and for a group of objects it is best to use a vector or DIY a resource management class.

14. Carefully coping the behavior in the resource management class:

(Raii-resource acquisition is initialization access to resources when initializing)

If a series of resources are managed in an object, we need to think about it when the object is copied.

A) prohibit copying, this simplest brute, direct copy constructor privatization.

b) Using the reference counting method for the underlying resource, Reference-count

c) Copy the resources from the bottom and copy the resource directly to the new resource management object.

d) Transfer of ownership of resources, that is, the original management of resources management resources management rights transferred to the object, the original management right to empty.

15. Provide access to the original resource in the Resource management class:

A) Although we use resource management classes to encapsulate resources, the vast majority of APIs do not recognize our own resource management classes, so to use this resource we must provide an external interface, in other words, a raw pointer to the resource or a reference to the outside.

b) For this interface, you can provide an explicit interface, such as the Get () method, to get the original pointer or reference. A more convenient approach is to provide an implicit conversion function (implemented with operator overloading). Both can be, the explicit conversion is more secure, the implicit conversion is more convenient.

16. The same form is used when using new and delete in pairs:

This is simple, that is, when new comes out, delete one, and when new sets, delete also releases a group. When you use [] when new, delete also adds [].

17. Place the Newed object in a smart pointer with a separate statement:

This one is relatively simple. is to first new out of an object, and then put it into the smart pointer, do not put these operations in a statement, otherwise, if there is an exception in the middle, the new object is empty, it is difficult to detect.

Two. Design and declaration

Programming for interfaces, not for programming. So the interface is grey and often important. The purpose of our interface design is to make the interface easy to use and not to be misused easily. Ensure correctness, efficiency, encapsulation, maintainability, ductility, and protocol consistency. The use of interface error-prone, not only because the use of people do not use, the design of the interface is also responsible for the person.

18. Make the interface easy to use correctly, not easy to misuse:

The simplest, if a function to receive a large string of parameters, if the type is different, maybe we write the wrong location of the compilation will be error, if the type is the same, then, even if the wrong location, compile will not error, the runtime will be unexpected. So the personal feeling, can pass the structure body or use the structure to pass the parameter bar, otherwise it is too disorderly.

Regarding the management of resources, whether the internal interface will involve the application of resources and release, the external to how to deal with, this is also to be noted.

19. The design class is like a design type:

If we think of our own class as a built-in data type, it seems that there are too many things we don't take into account. such as overloaded functions and operators, controlling memory allocations, object initialization and finalization, and so on.

A) How objects are created and released

b) Object initialization and object Assignment God horse difference

c) What happens if the object is pass by value

D) The legal value range of the object content

e) Whether you need to consider inheritance, if you inherit other classes, how to write virtual functions, if you want to inherit from other classes, whether to declare virtual functions, especially about virtual destructors.

f) What to do when facing a conversion type

g) What operators and functions are reasonable

h) What kind of function should not be exposed, what kind of system auto-generated function should be set to private to prevent exposure. Do you want a friend function

i) is sufficient generalization, if it is a type family, consider whether you need to use a template

j) Whether you really need to redesign a class, whether an existing class can derive the current class

20. Replace Pass-by-value with Pass-by-reference:

A) When passing by value, the copy constructor is called to construct a copy of the object, and when the scope of the function is out, the destructor is called to delete the object, such as a complex object that contains many fields and even other objects, so it is simply a disaster to pass such an object.

b) Also, if a parameter is passed by value, if the function parameter is a base class object, and the argument is an object of a subclass, then the arguments passed in will be cut, that is, only the copy of the base class is preserved (the argument becomes the object of a base class). The use of pass-by-reference can avoid this situation.

c) When pass-by-reference, it is generally necessary to use the Const keyword to qualify parameters, that is, within the function can not be passed in the parameters to modify. Of course, if you need to return a result by reference, you don't have to use Const.

d) Of course, although pass-by-reference is so useful, it's not always a good time to use this. When the parameter that we are passing is a built-in data type, it may be more efficient to use the pass-through value. It is also good for STL iterators and function objects to be passed directly.

21. When you must return an object, do not attempt to return its reference:

It says that passing parameters with reference or pointer is better, but when returning, what to do, imagine, a local object, we return to its reference or pointer, but the end of the function, the object is destroyed, Then if we use this reference or pointer, then the program will collapse!!!

See "Effective C + +" author wrote several "try to return to the local reference negative case", there is a direct return, certainly collapsed; The local new one returns again, then this object will not be properly refactored, and if there is a continuous call is more troublesome; , this is even worse, although the static object may seem to be on the surface of the value of unequal, but if the sentence with = =, it is necessarily equal.

Therefore, everything must have two sides, everything also has the meaning of existence. Use what you need, which is right, and don't overdo it.

22. Declare the member variable as private:

A) Most directly, if the member variable is private, then the only interface that accesses member variables is the function, which can save a lot of trouble, called encapsulation. The most direct meaning of encapsulation is that the variable can be accessed control, such as read-only, read-write and so on. Further, with encapsulation, if the internal member changes, the external does not need to be changed, reducing the coupling.

b) The package further guarantees "programming for the interface", the same class, which stores a series of properties internally, but exposes them to external interfaces, which can be implemented in many ways, giving us the flexibility to do so.

c) Again a gray useful place, when the member variable is modified, we can easily know that the variable is modified, because the only way to change the variable is this function, so long as the function inside a little bit to move.

D) If you do not encapsulate, those things that are constantly changing are called externally, so if you want to modify it, it is much more troublesome.

e) The protected type does not have much more encapsulation than public. Although protected can also provide encapsulation, it is public to the child class, and on the surface we do not have access to protected content, but if it changes, all its subclasses will suffer. No wonder someone said to use protected carefully!

23. Replace the member function with Non-member&&non-friend:

A) Although the content of the object is better encapsulated, however, the encapsulation of the variable is part of it, and if you need to call multiple member functions together, and then write a member function that contains these functions, the effect does not have a non-member function to accept the object, and then in a non-member function to call multiple functions effect good.

b) The non-member function referred to here refers to a member function that is not a class, can be a global function, does not belong to any one class, or it can be a member function of another class, it is not a friend function, the friend function destroys the encapsulation.

c) Why is this: since private already encapsulates what needs to be encapsulated, the exposed interfaces should all be used, then building a function that contains these interfaces internally is not a better way to encapsulate them, but it reduces flexibility.

D) After the design of a class, you can use the above method, in the same namespace with some of the tool functions used in the class, the tool function accepts a reference to a class, and then combines the invocation of some methods of the class, these methods are called convenience functions. These convenience functions can be in the same file as the class, so it is convenient and can be used directly. You can also be in different header files, and then use the same namespace, so that you can simply introduce some header files instead of introducing them all.

23. If all parameters require a type conversion, use the Non-number function for this:

A) This seems to be a lot of time about operator overloading, or an example is easier to see where the problem lies:

For example, a plural class supports the * operator overloading, operator* (), which is often used when we call, Obj1 *obj2, but actually this function is called obj1.operator* (OBJ2). At first glance there is no problem, but if so obj1.operator* (not an object of that type), this is the second object that will be converted to that object (provided that the conversion is supported), then the operation is still possible. However, if, in turn, objects other than that type are *obj1, this will be the case: objects other than that type. operator* (obj1), then the compiler will find objects other than the type of the operator* operator, no, look for the global operator, no, then, OK, collapsed.

b) To solve this problem is to provide a non-member function, because the above obj.operator* (obj) is equivalent to this operator* (Operator1, Operator2), with this function can avoid that type conversion, A special case of a particular function could not be found. In fact, the personal feeling is still this easy to understand, the above abstraction, and error prone.

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

Swap function, originally STL inside the standard library function, but I seem to have the basic wood useful. Take a look at this bar, to be honest, to serve, the author of this book is really a C + + Divine figure.

A) in terms of swap, simply swap two objects (or native data types). If all are objects, then the direct assignment is good, but if there are pointers or references, we should pay attention to the problem of shallow copy deep copy. However, if we design a class normally, the copy is designed to be a deep copy. For swap, you don't need a deep copy, he just swaps.

b) However, in the deep copy approach, that would be a new two object, which would be expensive, and the best way is to swap pointers directly in two objects. We can consider providing a swap function for an object.

c) directly with a non-member function that accepts two objects, there is no way to access the private object. So you can design a member function, and then call this function with the Non-member function.

D) This is not a complete step, because you have to make sure that the call to swap is the version we wrote, not the Std. Use a function to seal up the above non-member function, where using Std::swap. In this way, a direct call to swap, the compiler will call the best swap of the special, because we have defined this function, so we will call our own write the swap, and if there is no such swap, we call the standard swap, this is the STL inside that template definition, not specific, So you don't call this when you have your own swap. Note When you call swap, do not add any namespace prefixes.

f) Do not add custom stuff to Std.

h) This swap function is guaranteed for exceptional security, and it should never throw an exception.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Effective C + +" Reading notes (ii)

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.