What is smart pointer (Part 5 of solmyr's article series: Garbage Collection)

Source: Internet
Author: User
Lunch time.

Zero sat in front of the table, mechanically repeating the sequence of "food-> chew-> swallow", with an invisible big word on his face: I am absent-minded. Sitting on the opposite side of him, solmyr eats his lunch slowly, maintaining his consistent self-cultivation image-or, according to zero, those who are familiar with his nature: illusion.

"Why zero? Bad appetite ?", After filling his stomach, solmyr seems to be concerned about his apprenticeship.

"Well, nothing, just ...... Why does solmyr and C ++ not support garbage collection? (Note: Garbage collection is a mechanism to ensure that dynamically allocated memory blocks are automatically released, Java, and so on. Language Supports this mechanism .)"

Solmyr sighed and stared at zero with a calm look: "Is it better to have a quarrel with C ++ and Java on BBS? What's the argument? I told you earlier that such arguments are boring ."

"Er ...... Yes ", zero has to admit that although solmyr's eyes are not sharp at all, it somehow gives zero a slight fear.

"And who told you that C ++ does not support garbage collection ?"

"Ah! Solmyr, aren't you kidding me ?!"

"Zero, you have to change your mind. I ask you, C ++ does not support arrays that can dynamically change the size ?"

"This ...... Doesn't it seem like that ?"

"What is a vector ?"

"Er ......"

"Supporting a feature doesn't mean you have to add this feature Syntax We can also use the existing language mechanism to implement a library to support this feature. Taking garbage collection as an example, here our task is to ensure that every dynamically allocated memory block can be released, that is ......", Solmyr finds a piece of paper and a pen from nowhere, and writes:

Int * P = new int; // 1
Delete P; // 2

"That is to say, for every 1, we need to ensure that there is a 2 called, and 1 and 2 must appear in pairs. Let me ask you, is there anything in C ++ guaranteed by the language itself to appear in pairs ?"

"……", Zero is an expression that tries to search for memory, but it is clear that nothing is returned.

"The prompt is related to the creation of the class ."

"Oh! Constructor and destructor !"

"Correct. Unfortunately, normal pointers do not have constructor and destructor, so we must write a class to add a layer. Packaging , The simplest is like this :"

Class my_intptr
{
Public:
Int * m_p;

My_intptr (int * P) {m_p = P ;}
~ My_intptr () {Delete m_p ;}
};

............

My_intptr Pi (New INT );
* (PI. m_p) = 10;

............

"Here we can safely use my_intptr without worrying about memory leakage: Once the PI variable is destroyed, we know that the memory block pointed to by PI. P will be released. However, it would be too troublesome to access the my_intptr members each time. To this end, you can add an overloaded * operator to this class :"

Class my_intptr
{
PRIVATE:
Int * m_p;

Public:
My_intptr (int * P) {m_p = P ;}
~ My_intptr () {Delete m_p ;}

Int & operator * () {return * m_p ;}
};

............

My_intptr PI;
* Pi = 10;
Int A = * PI;

............

"Does my_intptr look like a real pointer now? Because of this, this technology is called a smart pointer. Now I ask you, what else does this class lack ?"

Zero frowned and blinked at it. It looked like a slow speed. Computer It is working hard to copy files to its hard disk. For a long time, zero raised his head and said, "Is there still a lack of copy constructor and a value assignment operator ?"

"Tell me why .", Solmyr obviously does not intend to let zero go.

"Because ...... I remember that ...... As mentioned in the book "50 commandments" (Note: Objective C ++ 2/E), if a pointer points to the dynamically allocated memory in your class, then you must write a copy constructor and a value assignment operator for it ...... Because ...... Otherwise, once you assign a value, the pointer of the two objects points to the same memory. Right! In this case, the same pointer is deleted twice !"

"Correct. So how should we implement it ?"

"This is simple. We use memcpy Target ."

"What if our smart pointer points to a class object? Note that the class object may have pointers, but memcpy is not allowed ."

"That ...... We use the copy construction method ."

"What if the object to which our smart pointer points cannot be copied and constructed? It may have a private copy constructor ."

"That ......", Zero paused and decided to honestly admit, "I don't know ."

"Where is the problem? Do you know? Because you didn't regard smart pointers as pointers. Imagine what it means if we assign a value to a pointer ?"

"Well, I understand. In this case, we should try to direct two smart pointers to the same object ...... But solmyr, why not delete the same object twice ?"

"Yes, we have to find a solution. Solution There are more than one way to solve this problem. The better one is to maintain a reference count value for each pointer. Each time a value is assigned or copied to the constructor, the Count value is incremented by one, this means that there is another smart pointer pointing to this memory block. Each time a smart pointer is destroyed, the Count value is reduced by one, this means that the smart pointer pointing to this memory block is missing; once the Count value is 0, the memory block is released. Like this :"

Class my_intptr
{
PRIVATE:
Int * m_p;
Int * m_count;

Public:
My_intptr (int * P)
{
M_p = P;
M_count = new int; // The initial count value is 1.
* M_count = 1;
}
My_intptr (const my_intptr & RHs) // copy the constructor
{
M_p = RHS. m_p; // point to the same memory
M_count = RHS. m_count; // use the same Count value
(* M_count) ++; // Add 1 to the Count value
}
~ My_intptr ()
{
(* M_count) --; // The Count value minus 1.
If (* m_count = 0) // No Pointer Points to this memory block
{
Delete m_p;
Delete m_count;
}
}

My_intptr & operator = (const my_intptr & RHs)
{
If (m_p = RHS. m_p) // first, determine whether it is directed to the same memory block.
Return * This; // Yes, return directly

(* M_count) --; // The Count value is reduced by 1 because the pointer no longer points to the original memory block.
If (* m_count = 0) // No Pointer Points to the original memory block
{
Delete m_p;
Delete m_count;
}

M_p = RHS. m_p; // point to the same memory
M_count = RHS. m_count; // use the same Count value
(* M_count) ++; // Add 1 to the Count value
}

............
};

"Nothing else has changed. I don't have to bother. How can we use this smart pointer ?", Solmyr put down his pen and picked up chopsticks again. Sorry, he found that his favorite meatballs were cold.

Zero was a bit hesitant. "We ...... You can use the new int expression as the parameter of the constructor to construct a smart pointer, and then ...... Then we can assign values at will. "He started to grasp the idea, and the faster he said," he can use existing smart pointers to construct new smart pointers, the value assignment operator, copy constructor, and destructor of smart pointers ensure that the Count value is always equal to the number of smart pointers pointing to the memory block." Zero seems to understand what he sees Function , Start to get excited: "Once the Count value is 0, the allocated memory block will be released! That is to say ...... If a pointer points to a memory block, it will not be released. Once it does not exist, it will be automatically released! Great! As long as we initialize the smart pointer correctly at the beginning, we can use it like a normal pointer, and there is no need to worry about the release of the internal memory! Great !" Zero shouted excitedly: "This is garbage collection! Solmyr! We have implemented a garbage collector on the dinner table !"

Solmyr apparently did not share Zero's excitement: "Can you not yell at me for a spam trap at the dinner table ?" After a pause, solmyr said in a nasty tone with his fake smile: "and pay attention to your image ."

"Hmm ?", Zero turned to him and found that he had no idea when to stand up, and the whole restaurant was watching him smile, which made him feel like a fool.

Zero sat down with a red face and lowered his voice and asked solmyr: "But solmyr, this is indeed a garbage collection mechanism. As long as we change this class ...... Hmm ...... Changed to a template class, as shown in the following figure: "Zero has caught a pen and paper and written:

Template <typename T>
Class my_ptr
{
PRIVATE:
T * m_p;
Int * m_count;
............
};

"Isn't it able to support any type of pointers? We can use it anywhere ."

Solmyr shook his head: "No, you think the problem is too simple. For a simple type, this class can indeed handle well, but the actual situation is very complicated. Consider a typical situation: the class derived is the derived class of the class base. We want to assign a value like this :"

Base * pb;
Derived PD;
............
PB = Pd;

"How do you use the smart pointer above to handle this situation ?"

"……", Zero is silent.

"It is not easy to implement a complete garbage collection mechanism because there are many details to consider .", Solmyr began to summarize, "however, the basic idea is as mentioned above. Fortunately, there is already a fairly mature 'reference count' smart pointer, boost: shared_ptr. In most cases, we can use it. In addition to smart pointers Technology It also helps us avoid the issue of releasing memory, such as the memory pool. However, the key lies in ---"

Solmyr again glances at zero with that calm:

"As a C/C ++ programmer, you must be creative. The kind of people who lie on the Language Mechanism and do not think aggressively, the kind of people who have to rely on grammar to know how to program, the kind of people who have no one to tell him what to do will be at a loss, this language is not suitable.

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.