We are going to define a structure that is composed of multiple members. Then, we allocate an instance of this structure on the heap that is maintained by a shared pointer. From this shared pointer, we obtain more shared pointers that do not point to the actual object but to its members:
- We include the necessary headers first and then declare that we use the std namespace by default:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
- Then we define a class that has different members. We will let shared pointers point to the individual members. In order to be able to see when the class is created and destroyed, we let its constructor and destructor print messages:
struct person {
string name;
size_t age;
person(string n, size_t a)
: name{move(n)}, age{a}
{ cout << "CTOR " << name << 'n'; }
~person() { cout << "DTOR " << name << 'n'; }
};
- Let's define shared pointers that have the right types to point to the name and age member variables of a person class instance:
int main()
{
shared_ptr<string> shared_name;
shared_ptr<size_t> shared_age;
- Next, we enter a new scope, create such a person object, and let a shared pointer manage it:
{
auto sperson (make_shared<person>("John Doe", 30));
- Then, we let the first two shared pointers point to its name and age members. The trick is that we use a specific constructor of shared_ptr, which accepts a shared pointer and a pointer to a member of the shared object. This way, we can manage the object while not pointing at the object itself!
shared_name = shared_ptr<string>(sperson, &sperson->name);
shared_age = shared_ptr<size_t>(sperson, &sperson->age);
}
- After leaving the scope, we print the person's name and age values. This is only legal if the object is still allocated:
cout << "name: " << *shared_name
<< "nage: " << *shared_age << 'n';
}
- Compiling and running the program yields the following output. From the destructor message, we see that the object is indeed still alive and allocated when we access the person's name and age values via the member pointers!
$ ./shared_members
CTOR John Doe
name: John Doe
age: 30
DTOR John Doe