Passing shared_ptr to a function

Feb 7, 2010 at 5:10am
Hi Guys,

I have a function,func1, which manages the data read from the socket. I am planning on taking a shared pointer to point to the received data. Now I also have to send this shared pointer to another function,func2 for some other task. So, should I pass in this shared pointer from func1 to func2 by value or should I use weak_ptr in func2 to store shared_ptr from func1.
I am sorry if this comes off as a really stupid question. The thing is that I really want to learn about smart pointers so I am trying to use them and I want to use them correctly.
Please correct me if my design seems bad.

Design 1
1
2
3
4
5
6
7
8
9
10

void func1() { 
   shared_ptr<base> sptr(new base()); 
   func2(sptr) ; 
} 

void func2(shared_ptr<base> ptr) { 

} 


Design 2

1
2
3
4
5
6
7
8
9
void func1() { 
   shared_ptr<base> sptr(new base()); 
   func2(sptr) ; 
} 

void func2(weak_ptr<base> wptr) { 

}


Thanks
Feb 7, 2010 at 11:15am
Both designs are correct.

Design 1 is simpler so I recommend it.
Feb 7, 2010 at 6:24pm
Does this mean that I can use weak and shared ptr interchangeably as function arguments?
Which one is the best practice?

Please let me know
Feb 7, 2010 at 6:45pm
shared_ptr and weak_ptr solve different problems and have different usages. You should pick
the one that matches the problem you are trying to solve. While you hold a non-NULL shared_ptr,
the pointer can never become NULL. On the other hand, a weak_ptr can become NULL
underneath you, and your code has to be able to deal with that. Obviously this is going to be
a little trickier to deal with, so you should probably avoid weak_ptr unless you need to break
a circular dependency.

Feb 7, 2010 at 7:16pm
Thanks for the clarification jsmith. Just one more question, is it a good idea to type cast shared_ptr to void pointer and then again use it as a shared_pointer ?

Thanks so much
Feb 7, 2010 at 8:37pm
Absolutely not.
Feb 7, 2010 at 8:39pm
Actually I wanted to use pointer in recv function. So should I stick with raw pointer and delete the memory after usage? or is there any other way that I can use smart pointer for this and avoid having to use raw pointer there?
Topic archived. No new replies allowed.