-2

**Update added main and cat

Hello all i am creating a sharedpointer class that has a reference counter.

What im trying to do is when i create a new object and give it value i can do so until i reach a cap of 3.

If i create anymore objects they will get NULL if i try to use obj.getPointer().

Currently when i try and create objects i get 0x22bd730 when i console log my main :(

m00se
  • 11
  • 4
  • You can use the ready made [std::weak_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr) in combination with the [std::shared_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr). – Ron Oct 12 '17 at 16:43
  • 1
    Please fix your indentation – AndyG Oct 12 '17 at 16:44
  • 1
    What problem are you trying to solve with this? What's the use case? – user0042 Oct 12 '17 at 16:48
  • This is for self practice to construct templates , classes and see how pointers can be shared. This is just for my personal education – m00se Oct 12 '17 at 17:03
  • 1
    in the assignment operator `*this = NULL;` seems an odd choice. What are you trying to do here? – user4581301 Oct 12 '17 at 17:06
  • it was me guessing my forward because naything i seemed to try resulted in still the pointer being there so i was just guessing what the cause was – m00se Oct 12 '17 at 17:13

1 Answers1

2

If you want to restrict to 3 references, your copy constructor and assignment should correctly act once limit is reached, something like:

sharedPTR(const sharedPTR<T>& ref) : myData(nullptr), myRef(nullptr)
{
    if (ref.myRef &&  ref.myRef->getCount() < 3) {
        myData = ref.myData;
        myRef = ref.myRef;
        myRef->AddRef();
    }
}

sharedPTR<T>& operator = (const sharedPTR<T>& ref)
{
    if (this == &ref) {
        return *this;
    }
    if (myRef && myRef->Release() == 0)
    {
        delete myData;
        delete myRef;
    }
    myData = nullptr;
    myRef = nullptr;
    if (ref.myRef && ref.myRef->getCount() < 3) {
        myData = ref.myData;
        myRef = ref.myRef;
        myRef->AddRef();
    }
    return *this;
}

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302