Question 16
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
#include <memory>
class Counter {
struct Impl;
std::unique_ptr<Impl> p_;
public:
Counter();
~Counter();
void hit();
int hits() const;
};
struct Counter::Impl { int hits = 0; int resets = 0; };
Counter::Counter() : p_(std::make_unique<Impl>()) {}
Counter::~Counter() = default;
void Counter::hit() { ++p_->hits; }
int Counter::hits() const { return p_->hits; }
int main() {
Counter c;
for (int i = 0; i < 4; ++i) c.hit();
std::cout << c.hits() << ' ' << sizeof(c) << '\n';
return 0;
}
- A 4 8 Correct
- B 4 16
- C 4 4
- D Compilation error
Correct Answer: Option A
All data lives in Impl on the heap; the Counter object itself is just one pointer (8 bytes on a 64-bit system), whatever Impl contains.
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!