LearnFrenzy
Sign in Take a free test

Static and Friend Members · Static and Friend Programs · Question 3

Count created and currently alive objects in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write a Session class with static counters for total sessions ever created and sessions currently alive, correct for copies and moves too, and show the counts at several points.

Solution
main.cpp
#include <iostream>
#include <memory>
#include <utility>
#include <vector>

class Session {
    static inline int total_ = 0, alive_ = 0;
    void born() { ++total_; ++alive_; }
public:
    Session()                   { born(); }
    Session(const Session&)     { born(); }
    Session(Session&&) noexcept { born(); }
    ~Session()                  { --alive_; }
    static void report(const char* when) {
        std::cout << when << ": total " << total_ << ", alive " << alive_ << '\n';
    }
};

int main() {
    Session a;
    {
        Session b = a;
        auto c = std::make_unique<Session>();
        Session::report("inside");
    }
    std::vector<Session> v;
    v.reserve(2);
    v.push_back(std::move(a));
    v.emplace_back();
    Session::report("end");
    return 0;
}

Output Verified by compiling and running

inside: total 3, alive 3
end: total 5, alive 3

Every way of creating an object – default, copy, move – calls born(), and every destruction decrements alive. At the end, a (moved from but still alive) and the two vector elements remain.

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