"C + +" C + + problem--Class template Detach compilation, function object, smart pointer

Source: Internet
Author: User

Separation and compilation of C + + class templates

In the past, many class templates were the whole class, along with the implementation, in a header file, such as the STL Library, which implements the class template by following such a strategy. The current standards are trying to rectify the situation.
There are many function templates in the implementation. This means that each function must contain a template declaration, and the name of the class must be instantiated by a template variable when using the scope operator.
For example, a operator= code:

template <typename Object>const MemoryCell <Object> &MemoryCell<Object>::operator=(const MemoryCell<Object> & rhs){    if(this != &rhs)    storeValue = rhs.storedValue;    return *this;}
Header file Contents

Putting the Declaration and implementation in the header file is not feasible for classes, because if several different source files have a containing directive that handles the header file, a duplicate definition of the function occurs. However, if the knowledge template in the header file is not the real class, then there is no problem.

Function object

In the writing of a function, the comparison function needs to be accepted as a parameter, and the comparison function is used to determine the size of two objects.
The reason for using this method is that the rule of comparison is stripped out of the object and is determined by a comparison function.
A clever way to transfer functions like passing parameters is to define a class that contains 0 data and a member function, and then pass an instance of the class. In effect, a function is passed by placing it in an object, which is often called a function object.
Example:
The Findmax function obtains a second formal parameter, which is a generic type. For the Findmax template to scale correctly, the generic type must contain a member function named Islessthan. This member function obtains two parameters for the first generic type and returns a bool value.

Template<TypeNameTTypeNameComparator>ConstT & Findmax (Const  vector<T>& arr, Comparator CMP) {intMaxindex =0; for(intI=1; I<arr.size (); i++)if(Cmp.islessthan (Arr[maxindex],arr[i])) Maxindex = i;returnArr[maxindex];}classcaseinsensitivecompare{ Public:BOOLIslessthan (Const string& LHS,Const string& RHS)Const{returnSTRICMP (Lhs.c_str (), Rhs.c_str ()) <0; }};intMain () { vector<string>Arr3); arr[0] ="Zerbad"; arr[1] ="Alligator"; arr[2] ="Crocodile";cout<< Findmax (arr, Caseinsensitivecompare ()) << Endl;return 0;}
Smart pointers

Classes that contain pointers require special attention to replication control, because copying pointers only copies the address of the pointer, not the object pointed to by the pointer.
When there are pointer members in a class, there are generally two ways to manage pointer members: One is managed by a value type, each class object retains a copy of the object pointed to by the pointer, and a more elegant way is to use a smart pointer to share the object that the pointer points to.
A common implementation technique for smart pointers (smart pointer) is to use reference counts (reference count). The smart pointer class links a counter to the object that the class points to, and the reference count tracks how many objects in the class have pointers to the same object.

Managing pointer members

When designing a class with pointer members, the designer of the class must first decide what behavior the pointer should provide. When you copy one pointer to another pointer, two pointers point to the same object. When two pointers point to the same object, you may use either pointer to change the underlying object. Similarly, it is possible that when one pointer deletes an object, the user of another pointer also thinks that the underlying object still exists.
Most C + + classes use one of the following three methods to manage pointer members:

  1. Pointer members use regular pointer-type behavior. Such a class has all the flaws of the pointer but does not require special replication control.
  2. Class can implement so-called "smart pointer" behavior. The pointer points to the object when it is shared, but the class prevents the dangling pointer.
  3. Class takes a value-type behavior. The object that the pointer points to is unique and is managed independently by each class object.
Pendant pointer

A class that has a pointer member and uses the default composition copy constructor, because the pointer is copied directly when the class is copied. The user must ensure that the object that the pointer points to exists as long as the class object exists. If the previously pointed object no longer exists, such a pointer is called a dangling pointer. Results are undefined, often resulting in program errors and difficult to detect. We can introduce smart pointers to prevent the appearance of dangling pointers.

For the specific contents of the smart pointer, please refer to the Smart pointer class and OPENCV PTR template class

The Non-const member function calls the const member function

In the writing of operator[] functions, what we want to do is to realize its function once and use it two times.
You have to make one of them call another. This prompts us to remove the constants .
When Const operator[] has completely done everything the Non-const version does, it is safe to convert the return value to const, because no matter who calls Non-const operator[] There must be a Non-const object, Otherwise, you cannot call the Non-const function. So non-const operator calls its const function as a safe way to avoid code duplication.

classa{ Public:Const Char&operator[](STD:: size_t position)Const{        ...        ...returnText[position]; }Char&operator[](STD:: size_t position) {return        const_cast<Char&> (static_cast<ConstA&> (* This) [position]); }Private:STD::stringtext;}

To make Non-const operator[] Call const operator[], but Non-const operator[] internal if only simply call operator[], it will call itself recursively. So we have to make it clear that the call is const operator[]. This transforms the *this from the original type a& to the const a&. This adds a const to the *this. Here we use static_cast for security transformation.
The second time is to remove the const from the return value of the const operator[]. This can only be done with const_cast.

If you call the Non-const function inside a const function, the logical state of the object is changed, so the const member function calls the NON-CONST member function as an error behavior, and the Non-const member function can do anything about its object. So calling a const member function in it does not pose a risk.

reprint Please indicate the author Jason Ding and its provenance
GitHub Blog Home page (http://jasonding1354.github.io/)
CSDN Blog (http://blog.csdn.net/jasonding1354)
Jane Book homepage (http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)
Baidu Search jasonding1354 access to my blog homepage

"C + +" C + + problem--Class template Detach compilation, function object, smart pointer

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.