LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 16

The shared_ptr aliasing constructor Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <memory>
#include <string>

struct Profile {
    std::string name = "Asha";
    int age = 21;
    ~Profile() { std::cout << "~Profile "; }
};

int main() {
    std::shared_ptr<int> age;
    {
        auto p = std::make_shared<Profile>();
        age = std::shared_ptr<int>(p, &p->age);    // points to a member, shares ownership of the whole Profile
        std::cout << p.use_count() << ' ';
    }
    std::cout << *age << ' ' << age.use_count() << ' ';
    age.reset();
    std::cout << '\n';
    return 0;
}
  • A 2 21 1 ~Profile Correct
  • B 1 21 1 ~Profile
  • C 2 ~Profile 21 1
  • D 2 21 0 ~Profile
Correct Answer: Option A

The aliasing constructor creates a shared_ptr that points to p->age but shares p's control block, so the whole Profile stays alive until age is reset.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links