C中的引用是一个convneint结构,允许我们简化以下C代码:
f(object *p){ //do something } int main(){ object* p = (object*) calloc(sizeof(object)); f(p); }
至
f(object& o){ //do something } int main(){ object o = object(); f(o); }
共享指针是C中另一种简化内存管理的便利.但是,我不知道如何将shared_ptr传递给f(object& o)这样的函数,它通过引用接受参数?
f(object& o){ //do something } int main(){ shared_ptr<object> p (new object()); f(*p); }
解决方法
按值获取shared_ptr,引用计数将增加.当你输入它时,这会更容易:
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! }
永远记住要正确,以防止错误:
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); }
我认为您应该尽可能将智能指针作为引用传递,以避免无关的增量和减量(以及副本和诸如此类的东西).