Solmyr article series 3: Object count (I)

Source: Internet
Author: User
The seats under the platform are full, except for the solmyr seats. Zero looked at the only vacant space and began to lament for 100th times why he fell into such an embarrassing position. Just a few minutes ago, everything went fine ............

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

HOST: "the next agenda is the c ++ Programming Technology lecture entitled 'object count'. The speaker is zero ."

Zero: "What ...... What ?! Wait a moment. Shouldn't this lecture be delivered by solmyr ?!"

HOST: "Well, it was originally mentioned by solmyr, but something is going to happen temporarily. before leaving, he will designate you to replace it. Didn't he tell you ?"

Zero: "He never mentioned it to me! I ...... I have not made any preparations! How can this be done? Are you kidding me ?!"

HOST: "You don't have to be modest. solmyr told me before leaving that you are fully qualified for this topic. By the way, there is a note he left for you ."

Zero opens the note, but as mentioned above, "50 commandments" (Note: it refers to the book "more effective C ++ 2/e"). How is it? If you have read it carefully, it will be okay. If you dare to refuse or make a mistake, hey ......"

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

"Alas !", Zero sighed and said, "in the face of reality, just put it on your head !" He decided to talk about the simplest part. It would be enough to get rid of the scene. He looked at the four big words "Object count" on the whiteboard and said, "Today ...... This ...... The topic discussed today is 'object count '. Object count ...... Ah ...... Calculate the number of objects in a class ".

The opening remarks were terrible. Zero thought it would be better to transfer the actual information as soon as possible.

"For this question ...... The simplest way is to add a static variable to the class to be counted, save the current number of objects, and increase or decrease the value of the variable by using the constructor and destructor, as shown in the following figure :"

Class wedget
{
Public:
Wedget () {m_count ++ ;};
~ Wedget () {m_count --;};

Int getcout () {return m_count ;};

PRIVATE:
Static int m_count;
};

Int wedget: m_count = 0;

Speaking, zero found that the incident was actually not so difficult. Instead, it felt that it had gradually entered the State and became fluent:

"The above practice is easy to understand: the static member variables in a class are shared by all objects in the class. When this class adds an object, the constructor will ensure that the Count value is plus one. When an object is destroyed, the Destructor will ensure that the Count value is reduced by one. The only note here is that if wedget is derived from a base class, the destructor of the base class must be declared as a virtual function. Why? Because we often use the base class pointer to operate on the objects of the derived class, this is the so-called "polymorphism" approach, one of the basic technologies of object-oriented programming. That is to say, the following types of code will be very common :"

Class base
......

Class wedget: public Base
......

Base * pb = new wedget; // The base class Pointer Points to the object of the derived class.
......

Delete Pb;

"But if the base destructor is not declared as a virtual function, when the delete Pb statement is executed, the compiler only knows that Pb is a pointer of the base * type, only the destructor of the base class will be called. As a result, the wedget class's destructor will be destroyed, but the wedget class's destructor will not be called, and an error will occur in the counting value. Therefore, the destructor of the base must be declared as virtual, And the compiler must judge the actual type of the object to ensure that the wedget class destructor are called ."

Zero paused, continued:

"By the way, this is a general principle of C ++ object-oriented programming ."

Zero looked around and found that everyone listened very seriously. Some people also showed an understanding of the expression, which increased his confidence and decided to continue:

"In a sense, now we have solved the 'object count' problem. But the process is not complete-we may have many classes that need to count objects. If we add the code to each class as above, this job is boring and prone to errors, so we need a general mechanism. The simplest, of course, is to encapsulate the above code into a class :"

Class counter
{
Public:
Counter () {m_count ++ ;};
~ Counter () {m_count --;};

Int getcout () {return m_count ;};

PRIVATE:
Static int m_count;
};

Int counter: m_count = 0;

"Then add a counter member to the classes to be counted, as shown in the following code :"

Class wedget
{
......
Counter m_mycounter;
};

"In this way, a new wedget object will add a counter object, and destroy a wedget object will destroy a counter object, which looks perfect. But ......", Zero dragged a long tone, "this solution is wrong !" After that, zero made a big cross on the whiteboard.

Zero was very satisfied with the dramatic effect of his actions when people were confused. He proudly explained:

"Because static members are shared by all objects in the class, if there is another class, for example, the other class also contains a m_mycounter member for counting, the wedget and other classes are actually sharing a Count value! Note that the m_mycounter member of wedget and the m_mycounter member of other are both counter class objects and share the same m_count static variable ."

"OK, to avoid this problem, you must use a small method, that is, the template:" Zero writes the following code on the whiteboard:

Template <class T>
Class counter
{
Public:
Counter () {m_count ++ ;};
~ Counter () {m_count --;};

Int getcout () {return m_count ;};

PRIVATE:
Static int m_count;
};

Template <class T>
Int counter <t>: m_count = 0;

Class wedget
{
......
Counter <wedget> m_mycounter;
};

Class other
{
......
Counter <other> m_mycounter;
};

"Do you see the difference? Counter <wedget> and counter <other> are two classes, so their m_count are independent. In this way, we implement separate counts for different classes ."

Zero turned around and was surprised to see that solmyr had appeared in his seat at some time, with his mouth carrying -- what? No, right? Zero finds that it is not a pop-up smile of solmyr, but a smile of support and approval. Zero cannot trust its own eyes. However, in a twinkling of an eye, the expression of solmyr is switched back to the familiar zero mode. The fast one thinks that what we saw just now is an illusion. The zero mind is sinking, and it seems a little bad to know --

"Let me give you a question .", Solmyr spoke, and the smile was brilliant ......
(To be continued)

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.