Thinking about new and memory address in C + +

Source: Internet
Author: User
Tags throw exception

OJ problem brush More, each time is directly allocated memory, then, you remember how to dynamically allocate memory?

————————————————————————————————————

We know that when using a function that allocates memory, such as malloc/calloc, it is important to check that its return value is a "null pointer" (that is, to check if the operation of allocating memory is successful), which is a good programming habit and necessary to write a reliable program. But if you simply apply the trick to new, it's not necessarily true.

in C + +, if new allocates memory fails, the default is to throw an exception . If you want to check if new is successful, you should catch the exception.

    Try {        intnewint[SIZE];         // other code    } Catch Const bad_alloc& e) {        return -1;    }

Of course, standard C + + also provides a way to suppress the new throw exception and return a null pointer:

    int New int // this way, if new fails, it does not throw an exception, but instead returns a null pointer        if (p==0 ) // So , this judgment is meaningful.            return -1;            // other code

—————————————————————— above are useless talk

New syntax format:new data type (initialize parameter list);

The difference between the new Plus () and the non-additive ():

When creating an object of a class with new, if a user-defined default constructor exists, then both new T and new T () will have the same effect, calling this default constructor, and if undefined, new T calls the system default constructor, new T () in addition to invoking the system default constructor, Assigns a value of 0 to the members of the base data type and pointer type , and the procedure is recursive. Even if a default constructor is not defined for a member object of the object, the base data type of the member object and the member of the pointer type are also assigned a value of 0.

So when using new, please add ().

The operator delete is used to delete the object created by new, releasing the memory space pointed to by the pointer.

——————————————————————

About objects of the new array type:

Syntax format: new type name [array length];

delete[] pointer name;

such as int* p = new int[10] ();

Delete[] p;

——————————————————————

Multidimensional Arrays:

Syntax format: New type name t[first dimension length [second dimension length] ...;

Where the 1th dimension is any expression that results in a positive integer, the rest must be a constant expression of a positive integer (because it is a constant, it cannot be assigned directly to an array of two-dimensional invariants).

If the memory request succeeds, it returns a pointer to the first address of the newly allocated memory, but not the T-type pointer, but a pointer to an array of type T , and the number of array elements is the product of the subscript expression in each dimension except the first dimension .

such as int (*p)[25][10]; Please take p out to see that p is of type int* [25][10]

p = new INT[10][25][10];

The pointer p can be used as a pointer or as a three-dimensional array name.

Another example is as follows:

int*p =New int[Ten];//returns a pointer to an int int*.int(*p) [Ten] =New int[2][Ten];//new A two-dimensional array that returns a pointer to a one-dimensional array of int[10] Int (*) [ten].int(*p) [2][Ten] =New int[5][2][Ten];//new A three-dimensional array that returns a pointer to a two-dimensional array, int[2][10], of this type, int (*) [2][10].

Note: New int[0][10] and new int[][10] are unallocated memory.

So what if the second dimension is not sure?

    int New int*[n];      for (int0; i < n; i++)         New int [n] (); // assign an array of n*n, also a[i] = new Int[i] (); a bit of Java flavor ...  for (int0; i < n; i++) Delete  [] a[i];  Delete[] A;  

Thinking about Delete: from Baidu know

When char * a=new char[10], the end of the program needs to delete [] A ask why you do not need to write delete [ten] A, that is how the computer knows the size of the array?
————————————————————————————————————————————————————————————————————————————————
As for new and delete, there always seems to be an endless topic to talk about.

First, after char * a=new CHAR[10], the system generally knows and records the size of the memory you are applying for. In turn, imagine if the system does not know how much memory you apply for, but when you delete[] the silly when you tell it, in case you accidentally pass a 1000000000 in, that still got?

In fact, if only to reclaim memory, C + + does not need to design a delete[],delete is enough. But delete is not just recycling memory, it is also responsible for calling destructors before that. Because it is a char type, there is no destructor, depending on the compiler you are using, the program will be OK, no crashes or no memory leaks (believe me, this is the case in VS2005), regardless of whether you use Delete or delete[].
However, if it is a class (or a struct with a destructor), the difference comes. The delete tells the compiler that you are releasing a single object, so the destructor is called only on the address of the object you are giving; delete[] tells the compiler that you want to release an array of objects, then the destructor is called for each object.
"Wait," you will say, "delete[" when I did not write the size of the array, the system how to know how many objects? "Well, the system certainly knows, just as it knows how much memory you're applying for." As early as you new[] (this time you have to write clearly how many objects you want), the system is quietly written down. Oh, no, that's what your dear C + + compiler did for you. Different compilers may be logged in different ways. Again with the lovely VS2005 example, if you use the new[] to generate an array of objects (to be refactored), it would have been possible to only need 100 bytes, but actually will apply 104 bytes, the extra 4 bytes, is used to save the length of the array. And with new, there's no such thing. This time, new[], delete[] must be paired so that the compiler knows that it will first find the array length, and then a destructor of an object.

Thinking about new and memory address in C + +

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.