【问题标题】:How To declare a variable in a class that will track the count of objects Created c++ [duplicate]如何在将跟踪对象计数的类中声明一个变量创建的c ++ [重复]
【发布时间】:2018-11-18 00:45:59
【问题描述】:

如何在一个类中声明一个变量来跟踪创建的对象的数量? 示例对象 obj; obj.object_count();

【问题讨论】:

  • 类中有一个静态变量,并在构造函数中递增。
  • 为什么要同时使用 Java 和 C++ 进行标记?

标签: c++


【解决方案1】:

您可以使用static 类成员存储对象计数。并在类构造函数中增加其值,在析构函数中减少其值。

请查找 cmets inline:

#include <iostream>
#include <atomic>

class Object
{
public:
    Object()    // Constructor
    {
        // initialize the object
        // ...

        m_objCount++;   // Increase object count when creating object (In constructor)
    }

    Object(const Object& obj)   // Copy constructor
    {
        m_objCount++;
    }

    Object(Object&&) // Move constructor
    {
        m_objCount++;
    }

    ~Object()
    {
        m_objCount--;   // Decrease object count when destroying object
    }

    static int object_count()   // Define a static member function to retrive the count
    {
        return m_objCount;
    }

private:
    static std::atomic_int m_objCount;  // Use static member to store object count, 
                                        // use std::atomic_int to make sure it is thread safe
};

std::atomic_int Object::m_objCount; // Initialize static member

int main()
{
    Object obj;

    // prints "obj count: 1"
    std::cout << "obj count: " << obj.object_count() << std::endl;          // call object_count() with object
    std::cout << "obj count: " << Object::object_count() << std::endl;      // call object_count() with class name
}

【讨论】:

  • 您还需要允许复制构造函数和移动构造函数。 OP 最好将此逻辑包装在一个类中,以便它的用户仍然可以遵循零规则
  • 既然object_count()static,你可以使用类类型而不是对象变量来调用它:fprintf(stdout, "obj count: %d\n", Object::object_count());为什么你在C++中使用fprintf()而不是使用std::cout ? std::cout &lt;&lt; "obj count: " &lt;&lt; Object::object_count() &lt;&lt; std:::endl;
  • 按建议编辑。
  • 如果你使用线程,你的计数应该是原子的
  • @AlanBirtles 你真的认为我们需要在这个问题中考虑多线程吗?
猜你喜欢
  • 2021-06-22
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 2017-10-30
相关资源
最近更新 更多