Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- template <typename T>
- class MySharedPointer{
- public:
- explicit MySharedPointer(T* pointer = nullptr){
- counter = new unsigned int(0);
- my_ptr = pointer;
- if (pointer)
- (*counter)++;
- }
- MySharedPointer(MySharedPointer<T>& other_sptr){
- counter = other_sptr.counter;
- my_ptr = other_sptr.my_ptr;
- if (other_sptr.my_ptr)
- (*counter)++; //increase counter in all instances
- }
- MySharedPointer<T>& operator=(const MySharedPointer<T>& other_sptr){
- if (this != &other_sptr){
- counter = other_sptr.counter;
- my_ptr = other_sptr.my_ptr;
- if (other_sptr.my_ptr)
- (*counter)++;
- }
- return *this;
- }
- ~MySharedPointer(){
- if (*counter == 0){
- delete my_ptr;
- delete counter;
- }
- else
- (*counter)--;
- }
- unsigned int getCount(){
- return *counter;
- }
- private:
- unsigned int* counter;
- T* my_ptr;
- };
- int main() {
- MySharedPointer<int> msp(new int(42));
- std::cout << msp.getCount() << std::endl;
- {
- MySharedPointer<int> msp2;
- msp2 = msp;
- std::cout << msp2.getCount() << std::endl;
- msp2 = MySharedPointer<int>(new int(17));
- std::cout << msp2.getCount() << std::endl;
- std::cout << msp.getCount() << std::endl;
- }
- std::cout << msp.getCount() << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement