C++ Primer 5th notes (chap 13 copy control) reference counting

Reference Count

1. Problem

Where is the counter stored? As a member of a class object, how to deal with copy construction?

Hasptr p1("Hiya");
Hasptr p2(p1);	
Hasptr p3(p1);	//p1,p2,p3指向相同的string

2. Solution

Each class object has a reference count, and the reference counts of all class objects guarantee unique synchronization.

class Hasptr
{
    
    
public:
    //2. 当创建一个对象时,只有一个对象共享状态,将此计数器初始化为1。
	Hasptr(const std::string &s = std::string()):
	ps(new std::string(s),
	i(0),
	use(new std::size_t(1)))	{
    
    }
	//3. 拷贝构造函数递增共享的计数器,指出给定对象的状态又被一个新的用户所共享。
	Hasptr(const Hasptr &p):ps(p.ps),i(p.i),use(p.use){
    
    ++*use}; 
	Hasptr& operator=(const Hasptr&);
	~Hasptr();
private:
	std::string *ps;
	int i;
	std::size_t *use;//1. 增加一个引用计数,用来记录有多少对象与正在创建的对象共享状态。
}

2. 1 Destructor

The destructor decrements the counter, indicating that there is one less user sharing the state. If the counter is 0, the destructor releases the state.

Hasptr ::~Hasptr()
{
    
    
	if(--*use == 0){
    
    
		delete ps;
		delete use;
	}
}

2. 2 overloaded assignment

The copy assignment operator increments the counter of the operand on the right and decrements the counter of the operand on the left. If the counter of the operand on the left is 0, it means that there are no users in its shared state, and the copy assignment operator must destroy the state.

Hasptr& Hasptr::operator=(const Hasptr& rhs)
{
    
    
	++*rhs.use;		//递增右侧对象的引用计数
	if(--*use == 0)	//递减和检测本对象的引用计数
	{
    
    
		delete ps;
		delete use;
	}
	
	ps = rhs.ps;
	i = rhs.i;
	use = rhs.use;
	
	return *this;
}

3. result

HasPtr h("hi mom!");
HasPtr h2 = h;  // no new memory is allocated, 
				// h and h2 share the same underlying string
HasPtr ret; 
ret = h; // HasPtr passed by value, so it is copied
cout << ret.i << "," << *ret.ps << endl;

Insert picture description here


【reference】

[1] Code referenceCount.h

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/113858495