解决了:
不能通过原指针增加引用次数的问题
,通过weak_ptr实现。
class MyCar:public std::enable_shared_from_this<MyCar> {
public:
~MyCar() {
std::cout << "free ~Mycar()" << std::endl;
}
};
int main()
{
MyCar* _myCar = new MyCar();
shared_ptr<MyCar> _myCar1(_myCar);
shared_ptr<MyCar> _myCar2 = _myCar->shared_from_this();
std::cout << _myCar1.use_count() << std::endl; //2
std::cout << _myCar2.use_count() << std::endl; //2
return 0;
}
错误用法:
智能共享指针不能够直接从this对象进行构造。
int main()
{
int* pt = new int();
shared_ptr<int> _p1(pt);
shared_ptr<int> _p2(pt);
std::cout << "_p1.use_count() = " << _p1.use_count() << std::endl; // 1
std::cout << " _p2.use_count() = " << _p2.use_count() << std::endl; // 1
return 0;
}
两次释放pt导致奔溃