LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 20

A custom deleter that logs Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

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

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

int main() {
    int freed = 0;
    auto deleter = [&freed](int* p) { std::cout << "free " << *p << ' '; ++freed; delete p; };
    {
        std::unique_ptr<int, decltype(deleter)> a(new int(1), deleter);
        std::shared_ptr<int> b(new int(2), deleter);
        auto c = b;
        std::cout << "| ";
    }
    std::cout << freed << '\n';
    return 0;
}
  • A | free 2 free 1 2 Correct
  • B | free 1 free 2 2
  • C | free 2 free 2 free 1 3
  • D free 1 free 2 | 2
Correct Answer: Option A

Locals are destroyed in reverse order: c (count drops to 1), b (count 0: its deleter frees 2), then a frees 1. Each object is deleted exactly once.

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