shared_ptr

209 阅读1分钟
  1. 通过引用计数来实现的。
  2. 一般来讲,应尽量用 make_shared来初始化及赋值。
  3. 根据2,this指针会非常麻烦。比如,我要把this 放到一个vector<shared_ptr> 中去。解决方法是 enable_shared_from_this 这样,就会变成共享一个shared_ptr了。(但需要注意:那个类的实例只能是以shared_ptr的形式来存放。 下面的代码引自cppreference.
struct Good: std::enable_shared_from_this<Good> // note: public inheritance
{
	std::shared_ptr<Good> getptr() {
		return shared_from_this();
	}
};

struct Bad
{
	std::shared_ptr<Bad> getptr() {
		return std::shared_ptr<Bad>(this);
	}
	~Bad() { std::cout << "Bad::~Bad() called\n"; }
};

int TestEnablemain()
{
	// Good: the two shared_ptr's share the same object
	std::shared_ptr<Good> gp1 = std::make_shared<Good>();
	std::shared_ptr<Good> gp2 = gp1->getptr();
	std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';

	// Bad: shared_from_this is called without having std::shared_ptr owning the caller
	try {
		Good not_so_good;//可以创建 static std::shared_ptr<T> Create() 且将 ctor设置为private 来解决这个问题。
		std::shared_ptr<Good> gp1 = not_so_good.getptr();
	} catch(std::bad_weak_ptr& e) {
		// undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
		std::cout << e.what() << '\n';
	}

	// Bad, each shared_ptr thinks it's the only owner of the object
	std::shared_ptr<Bad> bp1 = std::make_shared<Bad>();
	std::shared_ptr<Bad> bp2 = bp1->getptr();
	std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';
	return 0;
} // UB: double-delete of Bad
  1. 使用shared_ptr 进行强转,需要小心将原始指针释放掉。
int fu(shared_ptr<int> intPtr){
	return 0;
}

int main(){
	int *a = new int();
	*a = 1;
	fu(shared_ptr<int>(a));
	free(a);//这里崩,double free
	return 0;
}