std::enable_shared_from_this有什么用?
C++11及之后的标准推出了一个类std::enable_shared_from_this,这个类有什么用呢?很多文章讲得云里雾里,不知所以然。其实他的作用很简单,就是为一个类对象提供原生指针this对应的智能指针std::shared_ptr。
我们在使用原生指针(即A*之类的指针)时,经常需要返回一个类对象自身的指针,也就是this指针。现在,我们使用智能指针std::shared_ptr来替换原生指针,那么如何返回一个原生指针this对应的智能指针std::sahred_ptr呢?朴素的想法应该类似如下示例(文件命名为enable_shared_from_this.cpp):
#include <memory>
#include <iostream>
class Bad {
public:
std::shared_ptr<Bad> GetThisPtr() {
return std::shared_ptr<Bad>(this);
}
~Bad() {
std::cout << "Bad::~Bad() called\n"; }
};
void TestBad() {
// Bad, each shared_ptr thinks it's the only owner of the object
std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
std::shared_ptr<Bad> bad1 = bad0->GetThisPtr();
std::cout << "bad1.use_count() = " << bad1.use_count()

本文通过示例对比了std::enable_shared_from_this的作用,解释了如何避免智能指针std::shared_ptr在获取this指针时导致的双重释放问题。
最低0.47元/天 解锁文章
835

被折叠的 条评论
为什么被折叠?



