Search⌘ K
AI Features

- Examples

Explore practical examples demonstrating efficient resource management in Modern C++ using smart pointers. Learn how shared pointers handle resource lifecycles, the use of custom deleters, and how reference counting manages memory. This lesson prepares you to understand advanced memory control and introduces weak pointers to address cyclic reference issues.

We'll cover the following...

Example 1

To get a visual idea of the life cycle of the resource, there is a short message in the constructor and destructor of MyInt (line 8 - 16).

C++
// sharedPtr.cpp
#include <iostream>
#include <memory>
using std::shared_ptr;
struct MyInt{
MyInt(int v):val(v){
std::cout << " Hello: " << val << std::endl;
}
~MyInt(){
std::cout << " Good Bye: " << val << std::endl;
}
int val;
};
int main(){
std::cout << std::endl;
shared_ptr<MyInt> sharPtr(new MyInt(1998));
std::cout << " My value: " << sharPtr->val << std::endl;
std::cout << "sharedPtr.use_count(): " << sharPtr.use_count() << std::endl;
{
shared_ptr<MyInt> locSharPtr(sharPtr);
std::cout << "locSharPtr.use_count(): " << locSharPtr.use_count() << std::endl;
}
std::cout << "sharPtr.use_count(): "<< sharPtr.use_count() << std::endl;
shared_ptr<MyInt> globSharPtr= sharPtr;
std::cout << "sharPtr.use_count(): "<< sharPtr.use_count() << std::endl;
globSharPtr.reset();
std::cout << "sharPtr.use_count(): "<< sharPtr.use_count() << std::endl;
sharPtr= shared_ptr<MyInt>(new MyInt(2011));
std::cout << std::endl;
}

Explanation

  • In line 22, we create MyInt(1998), which is the resource that the smart pointer should address. By using sharPtr->val, we have direct access to the resource (line 23).

  • The output of the program shows the numbers of the reference counter. It starts in line 24 with 1. It then has a local copy shartPtr in line 28 and goes to 2. ...