Reference Counting

This is a discussion on Reference Counting within the C++ Programming forums, part of the General Programming Boards category; Why is it when reference counting, the copy-constructor increments this->counter but the copy-assignment increments ++*rhs.counter? I am unable to work ...

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    178

    Reference Counting

    Why is it when reference counting, the copy-constructor increments this->counter but the copy-assignment increments ++*rhs.counter?

    I am unable to work out in my head reasons for such. I understand that the std::shared_ptr increments the counter on both copy and assign.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    Well, in the assignment operator, before the assignment has taken place, incrementing the current objects counter would addref the wrong object. After the assignment happens it could addref the current object, but addrefing the right hand side is safer because it can be done before or after. All else being equal, it's therefore better to addref the right hand side. It quite possibly doesn't matter though, as long as this happens after the pointer assignment.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    178
    Thank you for your reply. Per my text, reference count increment/decrement happens prior to pointer assignment.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    Right so you understand why now then?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    178
    Quote Originally Posted by iMalc View Post
    Right so you understand why now then?
    Yes and thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reference Counting
    By GReaper in forum C++ Programming
    Replies: 3
    Last Post: 03-10-2010, 11:46 AM
  2. Reference Counting Template
    By BdON003 in forum C++ Programming
    Replies: 6
    Last Post: 11-26-2009, 01:18 AM
  3. Reference Counting
    By Dae in forum C++ Programming
    Replies: 10
    Last Post: 08-13-2009, 07:34 AM
  4. How to implement reference counting with 'Smart_ptr'?
    By meili100 in forum C++ Programming
    Replies: 3
    Last Post: 06-10-2007, 05:28 AM
  5. Replies: 6
    Last Post: 06-05-2007, 12:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21