Skip to content
This repository has been archived by the owner on Nov 19, 2022. It is now read-only.

Latest commit

 

History

History
124 lines (119 loc) · 4.12 KB

SharedPointer.md

File metadata and controls

124 lines (119 loc) · 4.12 KB

1. Challenge: Implement a Shared Pointer

Implement a shared pointer to an int in a class called SharedPointer. The specification for SharedPointer is given below:

Method Description Usage Exceptions
SharedPointer() A constructor which initialises a nullptr.
SharedPointer sp;
None
SharedPointer(int*) A constructor which initialises *this with ptr's resource.
int* ptr{new int{42}};
SharedPointer sp(ptr);
None
~SharedPointer() If *this is the last SharedPointer to the resource owned by *this, then the resource is destroyed.
int* ptr{new int{42}};
{
    SharedPointer sp1(ptr);
    SharedPointer sp2(ptr);
    SharedPointer sp3(ptr);
}
*ptr; // Invalid access.
None
int* get() Returns the stored pointer.
int* ptr1{new int{42}};
SharedPointer sp(ptr);
int* ptr2{sp.get()};
None
long use_count() Returns the number of SharedPointer managing *this's resource.
int* ptr{new int{42}};
SharedPointer sp1(ptr);
SharedPointer sp2(ptr);
SharedPointer sp3(ptr);
sp1.use_count() == 3;
None
int& operator*() Dereferences the stored pointer in *this.
int* ptr{new int{42}};
SharedPointer sp(ptr);
*sp == 42;
None

2. Challenge: Implement a Shared Pointer (Continued)

Take the SharedPointer class from lab03-1 and extend it with the following specification:

Method Description Usage Exceptions
SharedPointer(SharePointer const& sp) Copy constructor. The use count should increase by 1.
SharedPointer sp1;
SharedPointer sp2(sp1);
None
SharedPointer(SharePointer&& sp) Move constructor. The use count should not increase.
SharedPointer sp1;
SharedPointer sp2(std::move(sp1));
None
SharedPointer& operator=(SharePointer const& sp) Copy assignment. The use count should increase by 1.
SharedPointer sp1;
SharedPointer sp2;
sp2 = sp1;
None
SharedPointer& operator=(SharePointer&& sp) Move assignment. The use count should not increase.
SharedPointer sp1;
SharedPointer sp2;
sp2 = std::move(sp1);
None
friend bool operator==(SharedPointer const& lhs, SharedPointer const& rhs) Returns true if the values of the resources owned by lhs and rhs are the same.
int* ptr{new int{42}};
SharedPointer sp1(ptr);
SharedPointer sp2(ptr);
sp1 == sp2; // true
None
friend std::ostream& operator<<(std::ostream& os, SharedPointer const& sp) Outputs the value of the resource owned by *this.
int* ptr{new int{42}};
SharedPointer sp(ptr);
std::cout << sp; // &ptr
None