Memory traps: tame wild pointers in C + +

Source: Internet
Author: User
Tags bitwise constructor data structures

What is a wild pointer?

A mother has two children (two pointers), one in the kitchen, one in the bedroom, (belonging to different code blocks, whose lifetimes are different) the mother let the child in the kitchen bring a cake (the object pointed to) to the child in the bedroom, so that the child in the bedroom is willing to write homework. But the child in the kitchen was naughty, he ate the cake himself when he walked out of the kitchen and failed to bring it out. And in the bedroom did not eat cake, so refused to finish his homework. As a result, the mother did not know that the bedroom children did not eat cake, and thought the homework was over. The next day she was summoned to the office by the teacher. Things are in trouble.

In this way, the child in the bedroom is the wild pointer, because he did not get the cake he deserved, can not finish the homework the mother gave him.

This is the wild pointer that is spoken in C. The little script above is a demonstration of the most basic form of a wild pointer. The more likely scenario is that coder uses a free pointer when coding.

It is a relatively easy mistake for younger inexperienced coder to avoid such mistakes in the form of an experienced programmer, or to use reference counters to prevent the formation of wild pointers.

In short, in C, wild pointers may be wild, but they are also rule-based. But things have changed in C + +.

The coder are in greater trouble. C + + Programmers inevitably write many of these classes. Who makes C + + object oriented?

When we write classes, we inevitably use new to allocate memory to the class's data members. This is nothing, dynamic allocation of memory is a very common basic operation, we are learning data structures often do so, is not it?

But, man, it's not that simple. A class is an advanced user-defined data type that does not look much different from a user-defined type such as structure or enumeration. If you think so ...? Then you're going to die badly. Class is too complex to use, and it's not too much of a problem to work with objects of the class in general, but when you're copying an object, the problem comes.

For example, we know that when you initialize another object with one object, C + + is copied by bit, that is, an exact copy of the initialization object is created in the target object. This is enough in most cases. However, when your class is created, the memory is allocated for each object, which means that there is a new operation in the class. When your object is created, the class also assigns a chunk of memory to the object. If you use this object to initialize another object, the initialized object is exactly the same as the initialized object. This means that they use the same piece of memory instead of redistributing the memory for the object being initialized.

That would be a lot of trouble. If an object is destroyed, the allocated memory is destroyed (remember, the class is a destructor, and it is responsible for releasing dynamically allocated memory when the object is destroyed.) Did you say you don't write the destructor in the class? So poor child, then you go to another abyss, when your program is running for hours, the system will tell you that there is not enough memory. Imagine using your program on a Tencent server, and the other object is incomplete, like a pair of conjoined babies who share a portion of their organs, heart or liver. To save one is to sacrifice the other. One is sick, the other is going to suffer.

It can be said that this is the more abnormal in C + + wild pointers.

What the? You say I don't initialize objects with objects? So will we pass an object as a variable to a function? We do that many times. Sometimes we have to pass the object to a function by value, but you know what it means to pass by value? It means that a copy of the argument is passed to the function. This is no different from the initialization just now, in a bit copy, the object in the function body shared a memory with the object outside, even if the object in the function did not manipulate the memory, but when the function ended .... The destructor will be called ...

There is also the opposite situation ... when you want to return an object value within a function to an object outside, a temporary object is automatically generated that holds the return value of the function and passes the result to the target at the end of the function. So this temporary object is quickly created and quickly released ... A piece of memory was released two times. The consequences are unforeseeable.

When you assign the value of an object to another object, if you do not overload the assignment operator, it also results in a bitwise copy. The end result is a wild pointer (a cancer hidden within the class), or the same memory is released several times.

Did you see that? Are you scared? Do you feel that C + + is full of traps? There are not only traps, but dangerous goods everywhere. All C in the difficult problem, to C + + has become a general problem. OK, no nonsense, let's go on with the solution.

For this last assignment, we can only solve it by overloading the assignment operator, which is to avoid a bitwise copy.

As for the previous all belong to initialization, summed up is three kinds of situations:

1. When an object initializes another object, for example, in a declaration;

2. Transfer the Created object copy (by value) to a function;

3. When generating temporary objects, the most common is the return value of the function.

solves the problem of bitwise copying when initializing, and we solve it by creating a copy constructor.

The basic copy constructor form is:

ClassName (const classname &o)

{

Body here

}

Copy constructors are designed to address this problem.

Well, does everybody get it? Don't let your objects turn into poor Siamese people.

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.