2. (Shared Pointers) The objective of this exercise is to show shared ownership using smart pointers in

Question:

2. (Shared Pointers)

The objective of this exercise is to show shared ownership using smart pointers in C++.

Create two classes C1 and C2 that share a common heap-based object d as data member:

std::shared_ptr d;

Answer the following questions:

a) Create the code for the classes C1 and C2 each of which contains the shared object d above, for example:

class C1

{

private:

//double* d; OLD WAY std::shared_ptr d;

public:

C1(std::shared_ptr value) : d(value) {}

virtual ~C1() { cout << "C1 destructor";}

void print() const { cout << "Value " << *d; }

};

The interface for class C2 is similar to that of C1.

b) Create instances of these classes in scopes so that you can see that resources are being automatically released when no longer needed. To this end, employ the member function use_count() to keep track of the number of shared owners. This number should be equal to 0 when the program exits.

c) Carry out the same exercise as in steps

a) and

b) but with a user-defined type as shared data:

std::shared_ptr p;

d) Now extend the code in parts

a) to

c) to include the following operations on shared pointers: assigning, copying and comparing two shared pointers sp1 and sp2. Furthermore, test the following features (some research needed here):

 Transfer ownership from sp1 to sp2.

 Determine if a shared pointer is the only owner of a resource.

 Swap sp1 and sp2.

 Give up ownership and reinitialise the shared pointer as being empty.

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  book-img-for-question
Question Posted: