Question: 1. (First Encounters with Smart Pointers: Unique Pointers) Consider the following code that uses raw pointers: { // Block with raw pointer lifecycle double* d

1. (First Encounters with Smart Pointers: Unique Pointers)

Consider the following code that uses raw pointers:

{ // Block with raw pointer lifecycle double* d = new double (1.0);

Point* pt = new Point(1.0, 2.0); // Two-d Point class

// Dereference and call member functions

*d = 2.0;

(*pt).X(3.0); // Modify x coordinate

(*pt).Y(3.0); // Modify y coordinate

// Can use operators for pointer operations pt->X(3.0); // Modify x coordinate pt->Y(3.0); // Modify y coordinate

// Explicitly clean up memory (if you have not forgotten)

delete d;

delete pt;

}

Answer the following questions:

a) Type, run and test the above code. Introduce a try-catch block in which memory is allocated and directly afterwards an exception is thrown. You need to throw an exception in the body of the code. Since the code is not re-entrant, the memory is not reclaimed and hence it introduces a memory leak (in more general cases it would be a resource leak).

b) Now port the above code by replacing raw pointers by std::unique_ptr. Run the code. Are there memory leaks now?

c) Experiment with the following: initialising two unique pointers to the same pointer, assigning a unique pointer to another unique pointer and transferring ownership from one unique pointer to another unique pointer.

d) Use alias template (template typedef) to make the code more readable.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Accounting For Financial Instruments Questions!