Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8844843
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T11:35:16+00:00 2026-06-14T11:35:16+00:00

despite the ocean of smart pointer questions out there, I seem to be stuck

  • 0

despite the ocean of smart pointer questions out there, I seem to be stuck with one more. I am trying to implement a ref counted smart pointer, but when I try it in the following case, the ref count is wrong. The comments are what I think should be the correct ref counts.

Sptr<B> bp1(new B);       // obj1: ref count = 1
Sptr<B> bp2 = bp1;        // obj1: ref count = 2
bp2 = new B;              // obj1: ref count = 1, obj2: rec count = 1 **problem**

In my implementation, my obj2 ref count is 2, because of this code:

protected:
    void retain() { 
        ++(*_rc);
        std::cout << "retained, rc: " << *_rc << std::endl;
    }
    void release() {
        --(*_rc);
        std::cout << "released, rc: " << *_rc << std::endl;
        if (*_rc == 0) {
            std::cout << "rc = 0, deleting obj" << std::endl;
            delete _ptr;
            _ptr = 0;
            delete _rc;
            _rc = 0;
        }
    }

private:
    T *_ptr;
    int *_rc;

    // Delegate private copy constructor
    template <typename U>
    Sptr(const Sptr<U> *p) : _ptr(p->get()), _rc(p->rc()) {
        if (p->get() != 0) retain();
    }

    // Delegate private assignment operator
    template <typename U>
    Sptr<T> &operator=(const Sptr<U> *p) {
        if (_ptr != 0) release();
        _ptr = p->get();
        _rc = p->rc();
        if (_ptr != 0) retain();
        return *this;
    }

public:
    Sptr() : _ptr(0) {}
    template <typename U>
    Sptr(U *p) : _ptr(p) { _rc = new int(1); }

    // Normal and template copy constructors both delegate to private
    Sptr(const Sptr &o) : Sptr(&o) {
        std::cout << "non-templated copy ctor" << std::endl;
    }
    template <typename U>
    Sptr(const Sptr<U> &o) : Sptr(&o) {
        std::cout << "templated copy ctor" << std::endl;
    }


    // Normal and template assignment operator
    Sptr &operator=(const Sptr &o) {
        std::cout << "non-templated assignment operator" << std::endl;
        return operator=(&o);
    }
    template <typename U>
    Sptr<T> &operator=(const Sptr<U> &o) {
        std::cout << "templated assignment operator" << std::endl;          
        return operator=(&o);
    }
    // Assignment operator for assigning to void or 0
    void operator=(int) {
        if (_ptr != 0) release();
        _ptr = 0;
        _rc = 0;
    }

The constructor is initialized with a ref count = 1, but in my assignment operator, I am retaining the object, making the ref count = 2. But it should only be 1 in this case, because bp2 = new B is only one pointer to that object. I’ve looked over various smart pointer implementation examples, and I can’t seem to figure out how they deal with this case that I’m having trouble with.

Thanks for your time!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T11:35:18+00:00Added an answer on June 14, 2026 at 11:35 am

    From what I see of your code, you need a proper destructor in your smart pointer class to call release and fix the counter. You need at least that modification for your counter to work correctly.

    I didn’t see a Sptr(T *) constructor in your code, did you omit it?

    As a side note, I would probably use a std::pair to store the counter and the T pointer, but your data layout works as it is. As another answer pointed it out, you should pay attention to the self assignment case though.

    Here’s a minimal implementation following your data layout and interface choices:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    template <typename T>
    class Sptr {
    
    protected:
      T *_ptr;
      int *_rc;
    
      virtual void retain() {
        if (_rc)   // pointing to something
          ++(*_rc);
        clog << "retain : " << *_rc << endl;
      }
      virtual void release() {
        if (_rc) {
          --(*_rc);
          clog << "release : " << *_rc << endl;
          if (*_rc == 0) {
            delete _ptr;
            _ptr = NULL;
            delete _rc;
            _rc = NULL;
          }
        }
      }
    
    public:
      Sptr() : _ptr(NULL), _rc(NULL) {} // no reference
    
      virtual ~Sptr() { release(); }  // drop the reference held by this
    
      Sptr(T *p): _ptr(p) {  // new independent pointer
         _rc = new int(0); 
         retain();
      }
    
      virtual Sptr<T> &operator=(T *p) {
        release();
        _ptr = p;
        _rc = new int(0);
        retain();
        return *this;
      }
    
      Sptr(Sptr<T> &o) : _ptr(o._ptr), _rc(o._rc) {
        retain();
      }
    
      virtual Sptr<T> &operator=(Sptr<T> &o) {
        if (_rc != o._rc){  // different shared pointer
          release();
          _ptr = o._ptr;
          _rc = o._rc;
          retain();
        }
        return *this;
      }
    };
    
    int main(){
      int *i = new int(5);
    
      Sptr<int> sptr1(i);
      Sptr<int> sptr2(i);
      Sptr<int> sptr3;
    
      sptr1 = sptr1;
      sptr2 = sptr1;
      sptr3 = sptr1;
    
    }
    

    _rc is the indicator in your class that a pointer is shared with another instance or not.

    For instance, in this code:

     B *b = new B;
     Sptr<B> sptr1(b);
     Sptr<B> sptr2(b);
    

    sptr1 and sptr2 are not sharing the pointer, because assignments were done separately, and thus the _rc should be different, which is effectively the case in my small implementation.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Despite the accepted answer, I'm still hoping for a more detailed one, with examples.
Despite there are a lot of themes around this topic, I seem very frustrated
Despite many questions regarding this I cannot seem to find some code that works
Despite the number of similar questions, I haven't yet managed to find any such
Despite this being one of the best error messages I've ever seen (second only
Is there a way to force git to add a file despite the .gitignore
Despite my searching I can't seem to get good information. I just need to
Despite of doing it in each file type handler, is there any simple way
Despite the numerous attempts at trying to get this to work I'm stumped. I
Despite scouring previously asked questions of the same nature, and finding quite a few,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.