C++

Objectives :

  • File Name : string_new_delete2.cpp
    • memory allocation with new operator.
  • string pointer and array
    • *ptr1 passes value stored at a location on heap.
  • string array packet of 4 bytes.
  • Code:
 

Step: 1 Create a source file.

Step: 2 Edit and save Source file

Step: 3 Runtime Views: The reference of the string object "str1" was passed to a pointer with the address-of-operator (&str1). Here the pointer worked as a content-manager, and was monitoring on the stored value of "str1". When we deleted the allocated memories assigned to the pointer, "p1", as a result it emptied the content of the string object, str1".

Also note that the address of the pointer, p1, was changed from 0x3e2478 to  0x22ff40, but the address of pointer, p2, did not alter.

Step: Brief discussion

  • new operator prevents mutation:
    • The address of p2 changed but p1 retained it's address and did not flush.
    • With new operator, you can disengage the tie between two pointers.
  • passing string by reference
    • delete removes pointer created with new; if this pointer has the reference of a string, deleting pointer will delete the content of the string