shared_ptr의. 안전 및 편의 메모리 관리를 개선하기 위해 ++ 포인터 C 스마트 포인터. 다음 질문에 대한 강력한뿐만 아니라, 관심을 지불 :
1, 할당 일반 포인터를 사용할 수 없습니다
int* pIntValue = new int;
shared_ptr<int> shPtr= pIntValue; // 语法错误
shPtr = pIntValue; // 语法错误
동일한 데이터를 2 shared_ptr의 다중 참조 회 동일한 메모리의 방출을 초래할 것이다.
int* pIntArr = new int[10];
shared_ptr<int> sp1(pIntArr );
shared_ptr<int> sp2(pIntArr );// 析构时两次释放同一内存
3, shared_ptr의 포인터를 사용하여이 패키지를 가져올 수 있습니다.
오류 연습 :
class Test
{
public:
Test() {};
~Test() {};
public:
shared_ptr<Test> sget()
{
return shared_ptr<Test>(this);
}
};
Test one;
shared_ptr<Test> two= one.sget();// 两次释放t对象破坏堆栈
// 两次释放one对象破坏堆栈!!!!!
// 两次释放one对象破坏堆栈!!!!!
// 两次释放one对象破坏堆栈!!!!!
좋은 연습 :
class Test: public enable_shared_from_this<Test>
{
public:
Test() {};
~Test() {};
public:
shared_ptr<Test> sget()
{
return shared_from_this();
}
};
Test one;
shared_ptr<Test> two= one.sget();// 正确了。
도 4는, 메모리 누출 shared_ptr는 순환 참조.
class father;
class son;
typedef shared_ptr<father> father_ptr;
typedef shared_ptr<son> son_ptr;
class father
{
public:
~father() {}
son_ptr m_son;
};
class son
{
public:
~son() {}
father_ptr m_father;
};
father_ptr f(new father());
son_ptr s(new son);
f->m_father= s;
s->m_son= f;
F 레퍼런스 카운트는 카운트가 상기 shared_ptr의 0이 해제되면 조작이 명백하다 단순히이 케이스 (1)에 의한 카운트 만든 레퍼런스 카운트 후 (F)을 야기하고, 0이 아닌도 2 출구 s가 2이고 메모리 누수로 이어지는 해제되지 메모리에 포인트에요.
5 멀티 스레드 프로그램 shared_ptr의 용도.
class Test
{
public:
Test() {}
~Test() {}
// 更多的函数定义…
};
void thread_fun(shared_ptr<Test> sp)
{
// !!!在这大量使用sp指针.
shared_ptr<Test> tmp = sp;
}
shared_ptr<Test> sp1(new Test);
thread t1(bind(&fun, sp1));
thread t2(bind(&fun, sp1));
t1.join();
t2.join();
스마트 포인터를 액세스, 및 기타 유사한 스마트 포인터 할당에서 멀티 스레드 때문에 두 스레드가 운영 레퍼런스 카운트하는 동안 발생할 수있는 고장이나 잘못된 카운트 등의 경우이다.
클래스 weak_ptr를 사용하여 여러 스레드의 문제를 해결할 수 있습니다.
void fun(weak_ptr<Test> wp)
{
shared_ptr<Test> sp = wp.lock;
if (sp)
{
// 在这里可以安全的使用sp指针.
}
else
{
// 指针无效
}
}