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() << '\n';
} // Undefined Behaviour: double-delete of Bad
int main() {
TestBad();
return 0;
}
使用cmake
构建工程,CMakeLists.txt
文件内容如下:
cmake_minimum_required(VERSION 3.0.0)
project(enable_shared_from_this VERSION 0.1.0)
include(CTest)
enable_testing()
add_executable(enable_shared_from_this enable_shared_from_this.cpp)
# TARGET_LINK_LIBRARIES(enable_shared_from_this pthread)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
编译构建命令如下:
cd enable_shared_from_this
mkdir build && cd build
cmake .. && make
使用GDB挂载运行,命令如下:
gdb -q ./enable_shared_from_this
进入GDB界面后,按下r
运行程序,会得到如下崩溃信息:
Reading symbols from ./enable_shared_from_this...
(No debugging symbols found in ./enable_shared_from_this)
(gdb) r
Starting program: /home/zhiguohe/code/cpp_excercise/enable_shared_from_this/build/enable_shared_from_this
bad1.use_count() = 1
Bad::~Bad() called
double free or corruption (out)
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
输入bt
可查看当前的调用堆栈:
#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1 0x00007ffff7bd9859 in __GI_abort () at abort.c:79
#2 0x00007ffff7c4426e in __libc_message (action=action@entry=do_abort, fmt=fmt@entry=0x7ffff7d6e298 "%s\n")
at ../sysdeps/posix/libc_fatal.c:155
#3 0x00007ffff7c4c2fc in malloc_printerr (str=str@entry=0x7ffff7d70670 "double free or corruption (out)") at malloc.c:5347
#4 0x00007ffff7c4dfa0 in _int_free (av=0x7ffff7da3b80 <main_arena>, p=0x555555570eb0, have_lock=<optimized out>) at malloc.c:4314
#5 0x000055555555a399 in std::_Sp_counted_ptr<Bad*, (__gnu_cxx::_Lock_policy)2>::_M_dispose() ()
#6 0x000055555555982a in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() ()
#7 0x00005555555596a7 in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count() ()
#8 0x00005555555595c0 in std::__shared_ptr<Bad, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr() ()
#9 0x00005555555595e0 in std::shared_ptr<Bad>::~shared_ptr() ()
#10 0x0000555555559395 in TestBad() ()
#11 0x00005555555593ff in main ()
输入q
退出GDB界面。从上述调用堆栈可看出,Bad
对象内存存在双重释放,程序崩溃。
如果我们用如下方式实现,就可有效解决该问题:
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include <vector>
class Good : public std::enable_shared_from_this<Good> {
public:
std::shared_ptr<Good> GetThisPtr() { return shared_from_this(); }
~Good() { std::cout << "Good::~Good() called\n"; }
private:
friend void TestGood();
void Process(const std::string& msg) {
std::cout << "Good::Processing " << msg << '\n';
}
};
void TestGood() {
std::shared_ptr<Good> good0 = std::make_shared<Good>();
std::shared_ptr<Good> good1 = good0->GetThisPtr();
std::cout << "good1.use_count() = " << good1.use_count() << '\n';
// good0 and good1 must share ownership
assert(good0 == good1);
assert(!(good0 < good1 || good1 < good0));
std::weak_ptr<Good> self = good0->GetThisPtr();
auto func = [self](const std::string& msg) {
auto ptr = self.lock();
if (ptr) {
ptr->Process(msg);
} else {
std::cerr << "The object has been destroyed.\n";
}
};
std::vector<std::string> words = {"how are you", "have a nice day",
"wish you good luck",
"there are some funny animals"};
std::for_each(words.begin(), words.end(), func);
}
int main() {
TestGood();
return 0;
}
编译执行,结果如下:
good1.use_count() = 2
Good::Processing how are you
Good::Processing have a nice day
Good::Processing wish you good luck
Good::Processing there are some funny animals
Good::~Good() called
正常运行能取出this
指针对应的智能指针std::shared_ptr<Good>
,不会崩溃。
由此可见,std::enable_shared_from_this
的作用就是为一个类对象提供原生指针this
对应的智能指针std::shared_ptr
。