MCPcopy Create free account
hub / github.com/changkun/modern-cpp-tutorial / main

Function main

code/5/5.1.cpp:33–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

31//}
32
33int main()
34{
35 // auto pointer = new int(10); // 非法, 不允许直接赋值
36 // 构造了一个 std::shared_ptr
37 auto pointer = std::make_shared<int>(10);
38 auto pointer2 = pointer; // 引用计数+1
39 auto pointer3 = pointer; // 引用计数+1
40
41
42 foo(pointer);
43 std::cout << *pointer << std::endl; // 11
44 int *p = pointer.get(); // 这样不会增加引用计数
45
46 std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
47 std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
48 std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
49
50 pointer2.reset();
51 std::cout << "reset pointer2:" << std::endl;
52 std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
53 std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
54 std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
55
56 pointer3.reset();
57 std::cout << "reset pointer3:" << std::endl;
58 std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
59 std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
60 std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
61 // std::cout << *pointer << std::endl; // 引用计数为0时, 非法访问
62
63
64 // 离开作用域前,pointer 会被析构,引用计数减为0, 从而释放内存
65 return 0;
66}

Callers

nothing calls this directly

Calls 1

fooFunction · 0.70

Tested by

no test coverage detected