boost智能指针类似于C++11中的智能指针,详见https://blog.csdn.net/bureau123/article/details/116974697
下面简单的介绍boost中的智能指针
scoped_ptr
scoped_ptr类似于unique_ptr,独占所有权
#include<boost/scoped_ptr.hpp>
int main() {
boost::scoped_ptr<int> sp(new int);
*sp = 1;
*sp.get() = 2;
sp.reset(new int);
return 0;
}
scoped_array
使用方式和scoped_ptr类似,不同在于scoped_array用于存储动态数组,使用delete[]来释放堆上的内存
#include<boost/scoped_array.hpp>
int main() {
boost::scoped_array<int> sa(new int[2]);
sa[0] = 1;
sa[1] = 2;
return 0;
}
shared_ptr
类似于std中的shared_ptr
shared_array
shared_array就是shared_ptr可以存放动态数组的形式
boost::shared_array<int> sa1(new int[2]);
boost::shared_array<int> sa2 = sa1;
sa2[1] = 10;
std::cout << sa1[1] << std::endl;
weak_ptr
weak_ptr类似于std中的weak_ptr,只有和shared_ptr结合起来才有使用意义
#include<iostream>
#include<Windows.h>
#include<boost/shared_array.hpp>
#include<boost/weak_ptr.hpp>
DWORD WINAPI reset(LPVOID p)
{
boost::shared_ptr<int> *sh = static_cast<boost::shared_ptr<int>*>(p);
sh->reset();
return 0;
}
DWORD WINAPI print(LPVOID p)
{
boost::weak_ptr<int> *w = static_cast<boost::weak_ptr<int>*>(p);
boost::shared_ptr<int> sh = w->lock();
if (sh)
{
std::cout << *sh << std::endl;
}
return 0;
}
int main() {
boost::shared_ptr<int> sh(new int(99));
boost::weak_ptr<int> w(sh);
HANDLE threads[2];
threads[0] = CreateThread(0, 0, reset, &sh, 0, 0);
threads[1] = CreateThread(0, 0, print, &w, 0, 0);
WaitForMultipleObjects(2, threads, TRUE, INFINITE);
system("pause");
return 0;
}