智能指针
一、shared_ptr
1. reset 用法
#include <iostream>
#include <memory>
class SharedptrTest
{
private
:
int index_
;
public
:
SharedptrTest(int index
);
~SharedptrTest();
};
SharedptrTest
::SharedptrTest(int index
) : index_(index
) {
std
::cout
<< "SharedptrTest(" << index_
<< ")" << std
::endl
;
}
SharedptrTest
::~SharedptrTest() {
std
::cout
<< "~SharedptrTest(" << index_
<< ")" << std
::endl
;
}
int main(int argc
, char const *argv
[]) {
std
::shared_ptr
<SharedptrTest
> ptest
;
for (int i
= 0; i
< 3; i
++) {
std
::cout
<< "-------" << i
<< "------" << std
::endl
;
ptest
.reset(new
SharedptrTest(i
));
}
return 0;
}
g++ --std=c++11 shartdptr.cpp
-------0------
SharedptrTest(0)
-------1------
SharedptrTest(1)
~SharedptrTest(0)
-------2------
SharedptrTest(2)
~SharedptrTest(1)
~SharedptrTest(2)