what's the difference between shared_ptr and weak_ptr

R

raj s

When would you use which?

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
using boost::shared_ptr;
using std::cin;
using std::cout;
class a{
public:
boost::weak_ptr<a> class_member;

};


int main() {
shared_ptr<a> mainvar(new a);
cout<<mainvar.use_count();
mainvar->class_member = mainvar;
cout<<mainvar.use_count();
cout<<mainvar->class_member.use_count();
int a;
cin>>a;


}

in the above code weak_ptr is the must. Even when mainvar pointer goes
out of scope the reference count is still 1 since it is pointed by
class_member(shared_ptr)
to avoid this use class_member(weak_ptr) which in first does not
increase the reference count.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top