取值shared_ptr
,引用计数会增加。当你typedef
这样做时,这会更容易:
typedef boost:shared_ptr<object> object_ptr;
void foo(object_ptr obj)
{
obj->/* stuff*/;
obj.reset(); //only resets this local copy, that means:
// reduce reference count (back to 1), and
// set obj to point at null.
}
int main(void)
{
object_ptr obj(new object());
foo(obj);
}
请记住,引用是别名。当您通过引用传递时,您不会传递指针、副本等......,您正在为另一个对象起别名。(实际上它们是作为指针实现的):
typedef boost:shared_ptr<object> object_ptr;
void foo(object_ptr& obj)
{
obj.reset(); // the references was never increased, since a copy has not
// been made, this *is* obj in main. so the reference
// goes to 0, and obj is deleted
}
int main(void)
{
object_ptr obj(new object);
foo(obj); // after this, obj has been reset!
}
永远记住要const
正确,以防止错误:
typedef boost:shared_ptr<object> object_ptr;
void foo(const object_ptr& obj)
{
obj.reset(); // cannot do!
}
int main(void)
{
object_ptr obj(new object);
foo(obj);
}
我认为您应该尽可能将智能指针作为引用传递,以避免无关的增量和减量(以及副本等)。