以下指针集之间有什么区别?你何时在生产代码中使用每个指针,如果有的话?
示例将不胜感激!
scoped_ptr
shared_ptr
weak_ptr
intrusive_ptr
您是否在生产代码中使用了boost?
答案 0 :(得分:332)
答案 1 :(得分:90)
scoped_ptr 是最简单的。当它超出范围时,它就会被销毁。以下代码是非法的(scoped_ptrs是不可复制的),但将说明一点:
std::vector< scoped_ptr<T> > tPtrVec;
{
scoped_ptr<T> tPtr(new T());
tPtrVec.push_back(tPtr);
// raw T* is freed
}
tPtrVec[0]->DoSomething(); // accessing freed memory
shared_ptr 是引用计数。每次发生复制或分配时,引用计数都会递增。每次触发实例的析构函数时,原始T *的引用计数都会递减。一旦它为0,指针就被释放。
std::vector< shared_ptr<T> > tPtrVec;
{
shared_ptr<T> tPtr(new T());
// This copy to tPtrVec.push_back and ultimately to the vector storage
// causes the reference count to go from 1->2
tPtrVec.push_back(tPtr);
// num references to T goes from 2->1 on the destruction of tPtr
}
tPtrVec[0]->DoSomething(); // raw T* still exists, so this is safe
weak_ptr 是对共享指针的弱引用,需要您检查指向的shared_ptr是否仍然存在
std::vector< weak_ptr<T> > tPtrVec;
{
shared_ptr<T> tPtr(new T());
tPtrVec.push_back(tPtr);
// num references to T goes from 1->0
}
shared_ptr<T> tPtrAccessed = tPtrVec[0].lock();
if (tPtrAccessed[0].get() == 0)
{
cout << "Raw T* was freed, can't access it"
}
else
{
tPtrVec[0]->DoSomething(); // raw
}
当您必须使用第三方智能ptr时,通常会使用intrusive_ptr 。它将调用一个自由函数来添加和减少引用计数。请参阅link以提高文档以获取更多信息。
答案 2 :(得分:20)
在任何有关提升智能指针的调查中,不要忽略boost::ptr_container
。在例如std::vector<boost::shared_ptr<T> >
太慢的情况下,它们非常有用。
答案 3 :(得分:12)
我是关于查看文档的建议。它并不像看起来那么可怕。还有一些简短的提示:
scoped_ptr
- 指针超出范围时自动删除的指针。注 - 没有可能的分配,但没有引入任何开销intrusive_ptr
- 引用计数指针,没有smart_ptr
的开销。但是,对象本身存储引用计数weak_ptr
- 与shared_ptr
一起处理导致循环依赖的情况(阅读文档,在google上搜索以获得精美图片;)shared_ptr
- 智能指针的通用,最强大(和重量级)(来自boost提供的)auto_ptr
,可确保当控件离开作用域时,它指向的对象会自动销毁。然而,它具有与其他人不同的复制语义。unique_ptr
- will come with C++0x 回复编辑: 是