|
|
|
![]() |
|
|||||||
|
||||||||
![]() |
|
|
Thread Tools | Rate Thread | Display Modes |
|
|
|
#1
|
||||
|
||||
|
Re: C++ help: Understanding pointers?
Quote:
int* p = new int; code. As you deduced, it's practically useless. It uses at least twice the memory (4 bytes for the int, 4 bytes for your pointer p) of just declaring the integer normally, plus the 'new' operator incurs a significant performance penalty because the operating system has to hunt for enough space for your 4-byte allocation. What new does is it asks the operating system to reserve a certain amount of memory for your problem. In the case of "new int", it reserves 4 bytes (usually), then returns a pointer to those 4 bytes. What you usually use new for is things like this: int* buffer = new int[1000]; // allocates 1000 ints. This asks the operating system to allocate 1000 ints on the heap. Since you have limited space on the stack (where your conventionally-declared variables end up), you can't create really massive buffers there. In windows, a thread usually has a maximum stack size on the order of a few megabytes. If you're loading an image or a database, you often need far more than a few megabytes, so you need to store it on the heap (or be very clever). The stack is also far less flexible - you almost always have to know at compile-time how big your buffer needs to be, but if you're an "image-loading" program, you may have wildly varying buffer sizes for your decoded pixels. 'delete' tells the operating system you're done with a given block of memory on the heap. You can only delete things that you've told the operating system to allocate via 'new'. A very concrete example of why deleting is important is to make this program: int main(void) { while(true) { int* p = new int[100]; // allocate array, but never delete it p[5] = 5; } } Then open task manager - you'll see your program rapidly gobble up all the memory your system can give it, and eventually crash (new returns NULL when it can't find enough space for your request, and p[5] = 5 would try to write to invalid memory) To relate this to my book-page analogy - "int* buffer = new int[100]" is like saying "hey george, find me 100 consecutive blank pages, and tell me where the first page of that block starts". 'delete[] buffer' would say "hey george, I'm done with those 100 pages, you can let other people use them now". In this case, 'george' is my lame representation of the operating system. Related reading http://en.wikipedia.org/wiki/Dynamic_memory_allocation - all about why you might want new and delete http://en.wikipedia.org/wiki/New_(C%2B%2B) - new! Last edited by Bongle : 21-03-2012 at 21:08. |
![]() |
| Thread Tools | |
| Display Modes | Rate This Thread |
|
|