智能指针是线程安全的吗?
- 软件开发
- 2025-08-22 03:33:02

很遗憾,使用不当的时候并不是。 #include <iostream> #include <memory> #include <thread> #include <chrono> struct Foo { Foo(int i):i_(i){} void print() {std::cout << i_ << std::endl;} int i_; }; int main(int argc, char const *argv[]) { { auto shptr = std::make_shared<Foo>(42); std::thread([&shptr](){ std::this_thread::sleep_for(std::chrono::seconds(1)); shptr->print(); }).detach(); } std::this_thread::sleep_for(std::chrono::seconds(2)); return 0; } // g++ test.cpp -o test -lpthread // ./test // Segmentation fault
当我们向另一个线程传递智能指针的引用时,由于use count并没有加1,在shptr析构时直接销毁了管理的Foo实例,所以在线程中执行shptr->print()会引发coredump。 修改起来也很简单,把std::thread(&shptr改成std::thread(shptr即可。记住,智能指针尽量不要传引用。
知道在释放资源的时候shread_ptr和unique_ptr有什么不同吗?
这里需要在shared_ptr构造时传入deleter,用来销毁持有的数组,而unique_ptr无需此操作,因为unique_ptr重载了unique_ptr(T[])。
get_foo()方法为什么不直接返回this指针?
参考 ”为什么尽量不要使用裸指针初始化智能指针“。聪明的小伙伴,想想如果多次调用get_foo()会发生什么?
智能指针是线程安全的吗?由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“智能指针是线程安全的吗?”