The smart pointer contains two kinds of "shared_ptr" and "unique_ptr", because the two kinds of pointers are implemented differently, so the way to pass the deletion is different;
"shared_ptr" of the transfer of the deletion (deleter) way is relatively simple, only to add a specific name of the deletion function in the parameters, you can; Note is a single parameter function;
The "unique_ptr" is a function template (functions template), so you need to pass the type of the deletion in the template type (that is, function pointer), and then add a specific deletion in the parameter;
Defines the type of the function pointer, including three methods (typedef, typedef decltype, using), which can also be passed directly to the Decltype;
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/
Reference comments, the specific code is as follows:
* * * cppprimer.cpp * * Created on:2013.11.24 * author:caroline//*eclipse CDT, gcc 4.8.1*/
#include <iostream> #include <memory> using namespace std;
void Deleter (int* ptr) {delete ptr;
ptr = nullptr;
Std::clog << "shared_ptr Delete the pointer." << Std::endl;
int main (void) {//define function type typedef void (*TP) (int*);
typedef decltype (deleter) * DP;
Using up = void (*) (int*);
std::shared_ptr<int> SPI (new Int (a), deleter);
Std::shared_ptr<int> spi2 (new int, deleter);
Spi2 = std::make_shared<int> (15);
Std::cout << "*spi =" << *spi << Std::endl;
Std::cout << "*spi2 =" << *spi2 << Std::endl; Unique_ptr is the template function that requires the type of deletion (deleter), which is passed to the specific deletion std::unique_ptr<int, Decltype (Deleter) *> UPI (new int), deleter
); Std::unique_ptr<inT, tp> upi2 (new int (), deleter);
Std::unique_ptr<int, dp> upi3 (new int (), deleter);
Std::unique_ptr<int, up> upi4 (new int (), deleter);
Std::cout << "*upi =" << *upi << Std::endl;
Std::cout << "*upi2 =" << *upi2 << Std::endl;
Std::cout << "*upi3 =" << *upi3 << Std::endl;
Std::cout << "*upi4 =" << *upi4 << Std::endl;
return 0; }
Output:
shared_ptr deletes the pointer.
shared_ptr deletes the pointer.
shared_ptr deletes the pointer.
shared_ptr deletes the pointer.
shared_ptr deletes the pointer.
shared_ptr deletes the pointer.
*spi =
*spi2 =
*upi =
*upi2 =
*upi3 =
35
Author: csdn Blog spike_king