"C + +" smart pointer __c++

Source: Internet
Author: User
Tags assert
1. The role of intelligent pointers

The use of heap memory in C + + programming is a very frequent operation, and the application and release of heap memory are managed by the programmer. Programmers manage heap memory themselves can improve the efficiency of the program, but the overall management of heap memory is troublesome, C++11 introduced the concept of intelligent pointers to facilitate the management of heap memory. Use of common pointers, easy to cause heap memory leaks (forget to release), two releases, the program occurs when abnormal memory leaks and other issues, using smart pointers to better manage heap memory.

Understanding the smart pointer takes three levels: from a shallower perspective, the smart pointer encapsulates a common pointer using a technique called RAII (Resource Acquisition, initialization), which makes the smart pointer essentially an object and behaves like a pointer. The role of the smart pointer is to prevent forgetting to call Delete to release memory and program exceptions into the catch block forget to free memory. In addition, the timing of the pointer release is also very sophisticated, multiple release of the same pointer will cause the program crashes, these can be solved by the smart pointer. The smart pointer also has a role in translating value semantics into referential semantics. 2. Use of smart pointers

Smart pointers are available after the c++11 version, included in header file <memory>, Aauto_ptr,shared_ptr, Unique_ptr, weak_ptr 2.1, auto_ptr have many problems with the use of auto_ptr. Replication (copy constructor) and replication (operator =) is not supported, but error is not prompted when copying or assigning values. cannot be placed in a container because it cannot be replicated.
2.2, the use of shared_ptr

The

shared_ptr multiple pointers to the same object. SHARED_PTR uses reference counting, and each shared_ptr copy points to the same memory. Every time you use him, the internal reference count plus 1, each time the destructor, the internal reference count minus 1, minus 0 o'clock, automatically deletes the heap memory pointed to. The reference count inside the shared_ptr is thread-safe, but the object's reading needs to be locked. Class A smart pointer is a template class that can specify the type in which incoming pointers are initialized through constructors. You can also initialize using the Make_shared function. You cannot assign pointers directly to a smart pointer, one is a class, and the other is a pointer. For example, the std::shared_ptr<int> p4 = new int (1) is the wrong copy and assignment. The copy causes the object's reference count to increase by 1, assigning the original object reference count to minus 1, and automatically releasing the memory when the count is 0 o'clock. Later, the object reference count plus 1 points to the later object. Get function Gets the original pointer note Do not initialize multiple shared_ptr with a raw pointer, or it will cause two of times to free the same memory note avoid circular references, shared_ptr one of the biggest traps is circular reference, loop, circular reference can cause heap memory can not be properly released, resulting in memory leaks. Circular references are described in weak_ptr.

#include <iostream>
#include <memory>
using namespace std;

Share_ptr
int main (void)
{
		int a = ten;
		shared_ptr<int> Ptra = make_shared<int> (a);
		Shared_ptr<int> Ptra2 (Ptra);
		cout << ptra.use_count () << Endl;

		int b =;
		int *PB = &a;
		shared_ptr<int> PTRB = make_shared<int> (b);
		Ptra2 = PTRB;
		PB = Ptrb.get ();

		cout << ptra.use_count () << Endl;
		cout << ptrb.use_count () << Endl;
	}
	return 0;
}

the use of 2.2 unique_ptr

Unique_ptr "Unique" has its object, and only one unique_ptr at a time can point to a given object (by prohibiting copy semantics, only mobile semantics). Compared with the original pointer unique_ptr for its RAII, dynamic resources can be released in case of anomaly. Unique_ptr the life cycle of the pointer itself: starts when the unique_ptr pointer is created, until it leaves the scope. When you leave the scope, if it points to an object, it destroys the object it refers to (by default, the delete operator is used and the user can specify another action). Unique_ptr the relationship between the pointer and its object: within the life cycle of the smart pointer, you can change the object that the smart pointer refers to, such as when a smart pointer is created by a constructor, by a reset method, by releasing the ownership through the release method, and by transferring the ownership through the move semantics.

Unique_ptr
int main (void)
{
	{
		//Bind dynamic Object
		unique_ptr<int> uptr (new int);

		unique_ptr<int> uptr2 = uptr;		Cannot assign value
		//unique_ptr<int> UPTR3 (uptr);          Cannot copy

		unique_ptr<int> UPTR4 = Move (uptr);	   Conversion of Ownership
		uptr4.release ();		Free ownership
	}
	//Over uptr scope, memory release return
	0;
}


the use of 2.3 weak_ptr

WEAK_PTR is a smart pointer introduced to tie in with shared_ptr, because it does not have normal pointer behavior, does not overload the operator* and the, its biggest function is to assist shared_ptr work, as the bystander observes the use of resources. Weak_ptr can be constructed from a shared_ptr or another weak_ptr object to obtain observational rights of resources. However, WEAK_PTR does not have a shared resource, and its construction does not cause an increase in pointer reference counts. Using the WEAK_PTR member function Use_count () to observe the reference count of the resource, the function of another member function expired () is equivalent to Use_count () ==0, but faster, representing the observed resource (that is, the managed resources of the shared_ptr) has ceased to exist. Weak_ptr can manipulate resources by using a very important member function lock () to obtain an available shared_ptr object from the observed shared_ptr. But when expired () ==true, the Lock () function returns a shared_ptr that stores the null pointer.

weak_ptr
int main ()
{
	{
		shared_ptr<int> sh_ptr = make_shared<int>);
		cout << sh_ptr.use_count () << Endl;

		weak_ptr<int> wp (SH_PTR);
		cout << wp.use_count () << Endl;

		if (!wp.expired ())
		{
			shared_ptr<int> sh_ptr2 = Wp.lock ();
			*sh_ptr = m;
			cout << wp.use_count () << Endl
		}
	}
	return 0;
}

3. Design and implementation of intelligent pointer

Here is a demo of a simple smart pointer. A smart pointer class relates a counter to an object that the class points to, and a reference count tracks how many objects in the class share the same pointer. Initializes the pointer each time a new object of the class is created and a reference count of 1; When an object is created as a copy of another object, the copy constructor copies the pointer and increases the corresponding reference count; When an object is assigned, the assignment operator decreases the reference count of the object referred to by the left operand (if the reference count is reduced to 0, Deletes the object) and increases the reference count of the object referred to by the right operand; when the destructor is called, the constructor reduces the reference count (if the reference count is reduced to 0, the underlying object is deleted). A smart pointer is a class that simulates the action of a pointer. All smart pointers will overload the-> and * operators. Smart pointers also have many other features that are more useful for automatic destruction. This mainly utilizes the finite scope of the stack object and the temporary object (finite scope implementation) destructor to free the memory.

Analog implementation of smart pointer #include <iostream> #include <assert.h> using namespace std;
	Template<typename t> class Smartpointer {private:t *_ptr;
size_t *_count;
		Public:smartpointer (T *ptr = NULL): _ptr (PTR) {if (_ptr) _count = new size_t (1);
	else _count = new size_t (0);
			} smartpointer (const Smartpointer &ptr) {if (this!= &ptr) {this->_ptr = ptr._ptr;
			This->_count = Ptr._count;
		(*this->_count) + +;
		} smartpointer &operator= (Smartpointer &ptr) {if (this->_ptr = = ptr._ptr) return *this;
			if (this->_ptr) {(*this->_count)-;
				if (This->_count = = 0) {Delete this->_ptr;
			Delete this->_count;
		} this->_ptr = Ptr._ptr;
		This->_count = Ptr._count;
		(*this->_count) + +;
	return *this;
		} T & Operator* () {assert (this->_ptr = NULL);
	Return this->_ptr;
		} ~smartpointer () {(*this->_count)-; if (*this->_count = = 0) {Delete this->_ptr;
		Delete this->_count;
	} size_t Use_count () {return *this->_count;

}
};
	int main (void) {smartpointer<int> sp (new int (10));
	Smartpointer<int> SP2 (SP);

	smartpointer<int> SP3 (new int (20));

	SP2 = SP3;
	cout << sp.use_count () << Endl;
	cout << sp2.use_count () << Endl;
	cout << sp3.use_count () << Endl;
return 0; }

4, Common C + + Smart pointer interview

4.1, do you know the smart pointer? The principle of smart pointers.

Answer: The smart pointer is a class that passes in a normal pointer in the constructor of this class, releasing the incoming pointer in the destructor. The class of the smart pointer is an object on the stack, so when the function (or program) ends, it is automatically released.

4.2, commonly used smart pointers.

1) Std::auto_ptr, there are many problems. Copying (copy constructors) and assignments (operator =) is not supported, but error is not prompted when copying or assigning values. cannot be placed in a container because it cannot be replicated.

2) c++11 introduced Unique_ptr, also does not support replication and assignment, but better than auto_ptr, direct assignment will compile errors. If you really want to assign a value, you need to use: Std::move.

For example:

std::unique_ptr<int> P1 (new int (5));
std::unique_ptr<int> P2 = p1; Compilation can be wrong
Std::unique_ptr<int> p3 = Std::move (p1); Transfer ownership, now that memory is P3 all, p1 become an invalid pointer.

3 c++11 or Boost shared_ptr, a smart pointer based on reference count. It can be assigned at will, until the memory reference count is 0 and the memory is freed.

4) c++11 or boost weak_ptr, weak reference. Reference count There is a problem with referencing to form loops so that the two pointers to memory cannot be freed. Need to manually break the loop

Reference or use weak_ptr. As the name suggests, Weak_ptr is a weak reference, referenced only, not counted. If a piece of RAM is referenced simultaneously by shared_ptr and weak_ptr, when all shared_ptr

After the destructor, the memory is freed, regardless of whether or not weak_ptr references the memory. So weak_ptr does not guarantee that the memory it points to must be valid, before using it to check weak_ptr is

No null pointer.  4.3, the implementation of the smart pointer.
Reference article: https://www.cnblogs.com/wxquare/p/4759020.html https://blog.csdn.net/bian_qing_quan11/article/details/ 73333214

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.