why shared_ptr:
1)如果指针作为类成员时,使用shared_ptr封装原始指针,解决了复制类对象出现的问题(相较原始指针)。
如果是非内存资源(比如:互斥器),可以在构造时再传一个删除器(deleter)参数(shared_ptr可以,auto_ptr不能),因为shared_ptr缺省行为是“当引用计数为0时,删除其所指物”,那不是我们所想要的行为。
2)用于函数内部创建的堆对象的堆栈指针,作为函数返回值
how shared_ptr使用:《effective c++》item29
shared_ptr使用注意:
- 空指针解引用会运行时错误,触发宏BOOST_ASSERT(px != 0);
vs下:
#else
# include <assert.h> // .h to support old libraries w/o <cassert> - effect is the same
# define BOOST_ASSERT(expr) assert(expr)
#endif
typename boost::detail::sp_dereference< T >::type operator* () const
{
BOOST_ASSERT( px != 0 );
return *px;
}
# include <assert.h> // .h to support old libraries w/o <cassert> - effect is the same
# define BOOST_ASSERT(expr) assert(expr)
#endif
typename boost::detail::sp_dereference< T >::type operator* () const
{
BOOST_ASSERT( px != 0 );
return *px;
}
class A
{
public:
A():i_(0),j_(0){}
private:
int i_;
int j_;
};
int main()
{
shared_ptr<A> ptr1;
A obj(*ptr1);
system( "pause");
return 0;
}
- shared_ptr的定义问题
shared_ptr<int>
p1(new int(100)); 而不是
shared_ptr<int*> p1( new int (100)); //编译错误,应该为<int>
- 创建时传参为栈对象指针,或reset时传栈对象指针。离开作用域,即析构函数调用时,会引发运行时错误
A obj;
shared_ptr<A> ptr2(&obj); //运行时CRT 错误
或
A obj;
shared_ptr<A> ptr1( new A());
ptr1.reset(&obj); //运行时CRT 错误。
//如果是空指针即0,或原指针值,也会引发assert错误
- 智能指针构造时,不能用动态数组作为参数构造。
//《effective
c++ 》电子版p95
shared_ptr< int>
pi(new int[1024]); //可能会运行时错误。因为 shared_ptr用delete 析构而不是delete[]。若要封装动态数组,可以使用vector,string,scoped_arry,shared_array
auto_ptr<string> ps( new string[10]); // 可能会运行时错误。因为 auto_ptr用delete 析构而不是delete[]。若要封装动态数组,可以使用vector,string,scoped_arry,shared_array