0

I try to understand how atomic reference counting works but fail to grasp how reference counts propagate to all copies of an instance. Based on this question and on the boost reference I constructed the following code:

#include <atomic>
#include <iostream>
struct X {
    X() : ref_cout_(1){};
    mutable std::atomic<int> ref_cout_;
    X(const X* other) {
        other->ref_cout_.fetch_add(1, std::memory_order_relaxed);
    };
    ~X() {
        if (ref_cout_.fetch_sub(1) == 1) {
            std::cout << "relese main ressource " << std::endl;
        };
    }
    void print() { std::cout << ref_cout_.load() << std::endl; };
};

int main() {
    X* first = new X();
    X* second = new X(first); //ref count of first = 2; as expected
    X* third = new X(second);  // ref count does not seem to propagate to first
    first->print(); //prints :2. Strange
};

In this code above, the reference count of first is 1, then 2, and then still 2. For proper reference counting to work, I expected that creating object third would increase the reference count of all copies to three. I have thus the following questions:

  • How can I implement a reference counting facility that increases the reference count of all copies?
  • Why does the class use std::atomic<int> as reference count, and not `std::atomic<int*>?

I am grateful for all hints and suggestions!

fabian
  • 1,413
  • 1
  • 13
  • 24

0 Answers0