unique_ptr是C ++ 11中提供的智能指针。
弱指针与共享指针一起使用。您不能创建独立的唯一指针。
弱指针示例:
#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;
}
输出:
Reference Count = 1 Reference Count = 1
从输出中可以看到,引用计数没有增加。那是因为我们正在使用weak_ptr。如果我们使用了shared_ptr,则参考计数器将增加。
您也可以使用“wp”调用函数的指针弱。
shared_pointer的循环引用问题是什么?如何使用weak_ptr解决该问题?
当您有两个类A和B,其中A对B的引用与B对A的引用时,就会发生循环依赖性。
因此使用计数不会为零,因此不会被删除。
在这种情况下,请使用weal_ptr。因为它将不拥有对象的所有权,并且引用计数也不会增加。
例:
#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& p)
{
sP1 = p;
}
};
class B
{
shared_ptr<A> sP1;
public:
B() { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
void setShared(shared_ptr& 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;
}
输出:
A() B()
通过使用weak_ptr可以避免循环依赖性。
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |