c++variable-assignmentundefined-behaviorpointer-aliasing

Deallocating item in array


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?

Solution

  • 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").