Smart pointer (four) smart pointer and dumb class

Many C++ classes, including standard library types, have well-defined destructors that are responsible for cleaning up resources used by objects. Looking directly at this example, the following program may appear in a network library that uses a mixture of C and C++ languages. Because the C language has no concept of a destructor, it does not define a destructor, but uses a function to release the object.

struct destination; //要连接的对象
struct connection;  //表示此次连接
connection connect(destination * d);//调用connect将返回一个与destination的一个连接对象
void disconnect(connection);//断开连接的方法

We may use this library in a function:

void fun(destination &d)//传入一个引用
{
    
    
	connection c=connect(&d);//建立连接并
	//使用这个连接
	//忘记调用disconnect释放连接资源 
	//connection c局部对象在函数离开后再也找不到了
	//连接没有办法断开了
}

This is an overloaded form that can be constructed using smart pointers: shared_ptr<T> p(q,d)Add disconnect to the definition of the d object to control its destruction. Simply put, it is compatible with C without writing a destructor.

Guess you like

Origin blog.csdn.net/weixin_39258979/article/details/114045986
Recommended