Destructor & Pointers?

Hi,

This is probably a really straightforward (and potentially stupid) question. In a class, I've set a private double pointer called val. Now, in my constructor, I've made val an array and assign values to it.

My question is, in the destructor, if I set it to delete that array, will it just delete the array from the active memory and still store the values at the location of the pointer, or will it delete the array permanently?

Thank you
Last edited on
How do you "made val an array"?
Well I've used the line:
 
val = new double[nz];

If that helps clarify? Sorry!

nz taken in the constructor input arguments
Last edited on
You allocate dynamically with new double [nz] a block of memory from heap. The block is large enough to hold nz double values. Then you store the address of the block into variable val.

When you call delete [], you have to give it the address of a block that has been allocated with the new []. The block somehow knows how big it is. The block is deallocated, i.e. that part of memory addresses is no longer accessible by the program (actual error on unauthorized access depends on system).

In short: Yes. Gone. Kaputt. Marked unusable.


You use double. A built-in simple type. Complex types (classes) do have constructor and destructor. The new and delete not only allocate and deallocate; they do call constructor and destructor too. Destructors are called right before the memory becomes off-limits.
Last edited on
Ah, that's really helpful! Thank you so much. One last question, if I wanted to assign nz values to that (which I know), how would I go about that? I thought something like:

val = {0,3,2,1}

Would work but it seems wrong?
An assignment like that is wrong, because val is a pointer.

You should be able to initialize the array in the allocation statement with such brace syntax. Initialization is not quite the same as assignment.

However, a bigger question is: why new and a pointer? Why not a std::vector?
Topic archived. No new replies allowed.