How to use the C++ smart pointer unique_ptr
How to use C++ smart pointer unique_ptr, for this problem, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
1. Why do you need unique_ptr
Similar to shared_ptr, you need to solve memory leaks, but you don't need to use shared_ptr 's reference count, so you need such a smart pointer to reduce consumption. However, there will be new problems when using the obsolete auto_ptr. If the auto_ptr is copied and constructed or assigned, the copied auto_ptr will lose its function. At this time, it is necessary to disable the copy construction and assignment operation on the basis of auto_ptr, which is called unique_ptr.
two。 What is unique_ptr?
An unique_ptr exclusively owns the object it points to. That is, only one unique_ptr points to the same object at the same time, and when the unique_ptr is destroyed, the pointed object is destroyed. Using unique_ptr requires the introduction of
3.unique_ptr characteristics
Unique_ptr disables copy construction and assignment operations, which prevents the following operations from being completed.
Void testFunction (std::unique_ptr t) {t-> getString ();} void features () {/ / Disable copy from lvalue. / / unique_ptr (const unique_ptr&) = delete; / / unique_ptr& operator= (const unique_ptr&) = delete; / / cannot perform copy construction and assignment operation, which means that std::unique_ptr t (new Test) cannot be passed as a function parameter; std::unique_ptr T2 = t; / / compile error std::unique_ptr T3 (t); / compile error testFunction (t) / / compile error} 4. How to use unique_ptr4.1 simply use void simpleUse () {Test * test = new Test; std::unique_ptr t (test); qDebug ()