LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 12

A factory returning unique_ptr converted to shared_ptr Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 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 Logger {
    std::string name;
    explicit Logger(std::string n) : name(std::move(n)) {}
    ~Logger() { std::cout << "~" << name << ' '; }
};

std::unique_ptr<Logger> make_logger(const std::string& n) { return std::make_unique<Logger>(n); }

int main() {
    {
        auto a = make_logger("solo");
        std::shared_ptr<Logger> b = make_logger("team");
        auto c = b;
        std::cout << b.use_count() << ' ';
    }
    std::cout << '\n';
    return 0;
}
  • A 2 ~team ~solo Correct
  • B 1 ~solo ~team
  • C 2 ~solo ~team
  • D 2 ~team
Correct Answer: Option A

A returned unique_ptr converts into a shared_ptr. Locals are destroyed in reverse order: c, b (freeing team), then a (freeing solo).

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