0

It if have an object, lets call it o, and two arrays typeo *a,*b; if I assign o to both array a and array b then delete[] b what happens if I try to access o or o in a? For example:

struct name{int a;}
name *a = new name[1];
name *b = new name[1];
name o;
a[0] = o;
b[0] = o;
delete[] b;
a[0]; // what happens here?
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Hovestar
  • 1,544
  • 4
  • 18
  • 26

2 Answers2

2

If you just define int a[1] you are not allocating memory in heap, so no need to delete.

Otherwise if you create an array as follows: int *a= new int[1] , you have to delete as delete [] a;

By considering both above scenarios, you can safely access `a' after you delete b if you have allocated memory for b and a.

Steephen
  • 14,645
  • 7
  • 40
  • 47
1

In the example there are no problems. a[0] and b[0] are different objects in different memory locations, and destroying one of them has no effect on the other.

The new is a red herring; the following code works the same way:

name o;
name a = o;
{
   name b = o;
}

a;

name has value semantics, that is, copying it by value creates a wholly distinct copy. Built-in types such as int all have value-semantics too.

This code would only run into problems if o did not have value semantics; for example, if it contains a resource handle and does not contain copy-constructor and assignment-operator code for duplicating the resource handle.

Then copying o would make two objects with the same handle on that resource, and if o's destructor releases the resource it would leave a dangling copy.

To avoid these problems it is usually recommended to design all of your classes to have value semantics. If the class has a handle on a resource that is not duplicatable, then the class should have its copy-constructor and assignment-operator disabled to prevent inadvertant copies. In fact, the resource handle should be held by a class designed for resource handles.

This is sometimes known as "rule of three" (or since C++11, "rule of five" or "rule of zero").

M.M
  • 138,810
  • 21
  • 208
  • 365