C++ new question

Raziaar

I Hate Custom Titles
Joined
Sep 13, 2003
Messages
29,769
Reaction score
140
When exactly would one want to use the new command to allocate memory on the Heap instead of the stack? If I only have to manually manage heap memory, but I can create all my stuff on the stack, why exactly do I need to use new? And when would I want to use it?

Is it just about stack overflow, or what? I'm coming from C# to C++ btw.
 
In C++ I've been told to completely avoid pointers and use references, or where that's not possible to use a wrapped pointer. I.e. the message was "now that you have object-orientation, pointers a bad". Personally I think you'll see the use for pointers a lot more in C, where you have less of these fancy resources at your disposal.

An example of where you may want to allocate memory (and use a pointer) would be passing data to and from functions. Obviously in C++ you can pass a reference to a function, but in C that wasn't possible, so you had to create some memory you wanted your function to change and pass it in. However, you can't return a reference to an object created in your function, because it'll be destroyed when you return, so you create it on the heap and return a pointer to it, because you some particularly large objects you don't want to return by value.

Pointers can also be nice with things like arrays. You have the raw address of the data, so you can manipulate that address to get different items in the array. For this reason they're powerful, allowing you to do stuff you couldn't otherwise.

So I'd recommend C to 'grok' your pointers, but there are still plenty of reasons why pointers are useful. This C++ FAQ might help answer a few questsions. Here's a couple of paragraphs on references and pointers. Are you learning from a book, your course or the Internet?

Edit: Also, you can't dynamically allocate arrays without the use of the heap. At least, not in C and C++. I've barely touched C#, and it's been a while, so I'm assuming it's pretty much like Java. You can't, for instance, do something like this in C:

Code:
int size = 5;
int x[size];

Here you'd need to use new to allocate your space. It may be useful to think of the stack as allocated when the program is compiled. You can't, therefore, have a variable size piece of memory, otherwise how will it know how much to allocate when it compiles.
 
In C++ I've been told to completely avoid pointers and use references, or where that's not possible to use a wrapped pointer. I.e. the message was "now that you have object-orientation, pointers a bad". Personally I think you'll see the use for pointers a lot more in C, where you have less of these fancy resources at your disposal.

An example of where you may want to allocate memory (and use a pointer) would be passing data to and from functions. Obviously in C++ you can pass a reference to a function, but in C that wasn't possible, so you had to create some memory you wanted your function to change and pass it in. However, you can't return a reference to an object created in your function, because it'll be destroyed when you return, so you create it on the heap and return a pointer to it, because you some particularly large objects you don't want to return by value.

Hmmm... if your method returns the reference to the object and assigns it to the same type out of scope of the method, you won't be able to? And in C# we can pass objects as out paramter, which doesn't have to be initialized outside the method, and is instead initialized within.

Hrm actually now that does make sense, one I've woken up a bit more. In C#, all the objects we make are reference objects, with information on the stack. So simply passing the reference back would work... but I can see why it doesn't work now in C++ since you're passing the reference back, but it points to the object that was created in the method, which was on the stack and so it gets popped off and your reference is worthless and pointing to junk memory.

Okay okay... I see now.


Pointers can also be nice with things like arrays. You have the raw address of the data, so you can manipulate that address to get different items in the array. For this reason they're powerful, allowing you to do stuff you couldn't otherwise.

Yeah, I saw a little bit of pointer arithmetic. I couldn't exactly see the benefit at the time though, though I guess I can imagine it.

So I'd recommend C to 'grok' your pointers, but there are still plenty of reasons why pointers are useful. This C++ FAQ might help answer a few questsions. Here's a couple of paragraphs on references and pointers. Are you learning from a book, your course or the Internet?

Thanks man, I'll check it out. I typically learn my stuff from books and tutorials. I've been learning a bit of C++ from the stanford course, but I haven't been able to get their libraries to work in my version of visual studio, and so I kind of stopped with that, for now.

Edit: Also, you can't dynamically allocate arrays without the use of the heap. At least, not in C and C++. I've barely touched C#, and it's been a while, so I'm assuming it's pretty much like Java. You can't, for instance, do something like this in C:

Code:
int size = 5;
int x[size];

Here you'd need to use new to allocate your space. It may be useful to think of the stack as allocated when the program is compiled. You can't, therefore, have a variable size piece of memory, otherwise how will it know how much to allocate when it compiles.

Hmm... I haven't had a whole lot of experience yet with C++ arrays. I did hear that they are rather... clunky to work with. No bounds checking, among some of the things you mentioned as well. Makes sense though.


Hey Druckles, I appreciate you responding to the thread man. :thumbs:
 
That makes sense. I haven't had to really worry about memory management with C#(and most things were stored on the heap anyway), and so learning C++ helps me understand those things and get a better grasp of computers and programming in general.

Thanks man.
 
I'm not too familiar with C++, but many C++ programmers seem to be big on RAII for resource handling. I think the basic principle is to basically never call new/malloc/delete in user code, but that you make use of stack allocation and destructors to clean up resources.

Yeah, I saw a little bit of pointer arithmetic. I couldn't exactly see the benefit at the time though, though I guess I can imagine it.

It can be used for example for reinterpreting data, like treating an array of ints as an array of bytes, by not indexing into the array with an int, but with a byte and you need pointer arithmetic for that. Say that you have an array of ints, that represent colors and you want to convert this to an array of ARGB bytes. Without pointer arithmetic, it would look like:

Code:
static void ToARGB(uint[] source, byte[] dest)
{
  for (int i = 0; i < source.Length; i++)
  {
    var current = source[i];
    dest[i * 4] = (byte)(current >> 24);
    dest[(i * 4)+1] = (byte)(current >> 16);
    dest[(i * 4)+2] = (byte)(current >> 8);
    dest[(i * 4)+3] = (byte)(current);
  }

}

However, with pointer arithmetic, you can do it like this:

Code:
static unsafe void UnsafeToARGB(uint[] source, byte[] dest)
{
  fixed (uint* srcPtr = source)
  fixed (byte* destPtr = dest)
  {
    var ptr = (uint*)destPtr;

    for (int i = 0; i < source.Length; i++)
    {
      ptr[i] = srcPtr[i];
    }
  }
}

The above is C#, but it's true of C++ as well. There's no logic there to convert an int to a byte through bit-masking, it just says "this piece of memory here, treat it as a uint". It's all just numbers in memory after all. As such, it's more than twice as fast.
 
Hmmm.... interesting stuff. I don't full have my head around it yet(regarding the pointer arithmetic0, but thanks for the input!
 
Back
Top