LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Predict the Output · Question 20

Counting live objects with constructors and destructors 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?

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

struct Live {
    static inline int n = 0;
    Live() { ++n; }
    Live(const Live&) { ++n; }
    ~Live() { --n; }
};

int main() {
    Live a;
    Live b = a;
    auto p = std::make_unique<Live>();
    std::cout << Live::n << ' ';
    {
        Live c, d;
        std::cout << Live::n << ' ';
    }
    p.reset();
    std::cout << Live::n << '\n';
    return 0;
}
  • A 3 5 2 Correct
  • B 2 4 2
  • C 3 5 3
  • D 3 3 2
Correct Answer: Option A

a, its copy b, and the heap object make 3; c and d raise it to 5 inside the block; after the block and p.reset() only a and b remain. The copy constructor must also increment, or the count would drift.

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