unique_ptr is a smart pointer available in C++ 11.
Weak pointer is used along with shared pointers. You cannot create a standalone unique pointers.
Example of weak pointer:
#include<iostream>
#include <memory>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;
class MyClass
{
public:
MyClass()
{
}
~MyClass()
{
}
};
int main()
{
shared_ptr<MyClass> p (new MyClass);
cout<<"Reference Count = "<< p.use_count()<<endl;
weak_ptr <MyClass> wp = p; // created a weak pointer
cout<<"Reference Count = "<< p.use_count()<<endl;
return 0;
}
Output:
Reference Count = 1
Reference Count = 1
As you can see form the output, the reference count is not increased. That is because we are using weak_ptr. If we have used shared_ptr, the reference counter will be incremented.
You can also use “wp” weak pointer to call the functions.
What is cyclic dependency problem with shared_pointer and how it can be solved using weak_ptr?
Cyclic dependancy will occur when you have two classes A and B where A has a reference to B which has a reference to A.
Example:
#include<iostream>
#include <memory>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;
class B;
class A
{
shared_ptr<B> sP1; // use weak_ptr instead to avoid cyclic dependancy
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void setShared(shared_ptr<B>& p)
{
sP1 = p;
}
};
class B
{
shared_ptr<A> sP1;
public:
B() { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
void setShared(shared_ptr<A>& p)
{
sP1 = p;
}
};
int main()
{
shared_ptr<A> aPtr(new A);
shared_ptr<B> bPtr(new B);
aPtr->setShared(bPtr);
bPtr->setShared(aPtr);
return 0;
}
Output:
A()
B()
The cyclic dependancy can be avoided by using weak_ptr.