#include <thread>
#include <memory>
#include <Windows.h>
int main()
{
    std::thread t;
    {
        std::shared_ptr<int> p(new int(1), [](int* p) { printf("delete\n"); delete p; });
        t = std::thread([&]() {Sleep(10000); printf("*p:%d\n", *p); });
    }
    Sleep(20000);
    t.join();
    system("pause");
    return 0;
}

上面使用引用传参,打印结果为:

证明:C++ std::shared_ptr的引用不会增加它的计数值

 

 证明了智能指针的引用不会增加智能指针的引用计数。下面换成 将智能指针用值传递,也就是发生拷贝:

#include <thread>
#include <memory>
#include <Windows.h>
int main()
{
    std::thread t;
    {
        std::shared_ptr<int> p(new int(1), [](int* p) { printf("delete\n"); delete p; });
        t = std::thread([=]() {Sleep(10000); printf("*p:%d\n", *p); });
    }
    Sleep(20000);
    t.join();
    system("pause");
    return 0;
}
打印结果为:
证明:C++ std::shared_ptr的引用不会增加它的计数值

 

只有在std::shared_ptr发生copy时,计数才会增加,而在增加它的引用(&)时,计数不会增加。

新手容易混淆的点,这里搞错很容易在传参时引用已经销毁了的资源,导致程序崩溃哦。

 


相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-10
  • 2021-05-23
  • 2021-06-02
  • 2022-01-21
猜你喜欢
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2021-05-30
  • 2021-04-14
  • 2021-05-04
  • 2022-02-19
相关资源
相似解决方案