46. Access Object with shared_ptr

We have already defined a class Logger with a method:

void log() { cout << "Logging data\n"; }

 

Your task is to:

  1. Declare a shared_ptr<Logger> object in main().
  2. Create a second shared_ptr that shares ownership of the same Logger object.
  3. Call the log() method using both shared pointers.

     

Example

Output:

Logging data
Logging data

 

Why this output?

Both shared pointers (p1 and p2) point to the same Logger object, so calling log() through each produces two identical lines.

 

Question Significance

This demonstrates how multiple smart pointers can share ownership of a single object, unlike unique_ptr which has only one owner.

Loading...

Input

Expected Output

Logging data Logging data