0

我正在开发一个项目,该项目必须允许创建的所有实例都具有唯一的 objID。所有类都继承自一个基类,该基类具有一个静态变量,每当调用任何具体类的构造函数时,该变量都会递增。计数器一直运行直到程序退出。

我遇到的问题是,当我使用数组(任何 C++ 容器)时,objID 注册的增量超过一个。

例如:在我的main()我创建了一个vector<ConcreteClassA> cc;并做了push_back(...)两次。

我的输出是:

objID = 5, and count = 2

预期结果:

objID = 2, and count = 2

我不知道为什么我ObjID的每个注册都不止一次push_back(...)。我已经检查并检查了所有位置,以确保assign()仅在我的具体类的构造函数中调用 my 。

请指教。

//===========================================================================   
//Main.cpp

#include "ConcreteClassA.h";

#include <iostream>
#include <vector>
#using namespace std;

int main()
{
    vector<ConcreteClassA> c1;
    cc.push_back( ConcreteClassA() );
    cc.push_back( ConcreteClassA() );

    return 0;
}

    //objID is off for some reason....
    //Expected Results: count = 2, objID = 2
    //Output: count = 2, objID = 5

//===========================================================================
//IBase.h file
private: 
    static int objID;      //used to assign unique IDs
    static int count;      //track how many stances of all objs are active

protected:        
    const int assignID();  //return a new ID
    void decrementCount(); //decrement count, when an obj is removed
//===========================================================================

//IBase.cpp
int IBase::objID = 0;
int IBase::count= 0;

const int IBase::assignID()
{
    ++ this->count;
    ++ this->objID;

    return ( this->objID );
}

void IBase::decrementCount()
{
    -- this->count;
}

//===========================================================================
ConcreteClassA.h

ConcreteClassA();     //default constructor
ConcreteClassA(...);  //couple overloaded constructors
~ConcreteClassA();    //destructor

ConcreteClassA( const ConcreteClassA &cc );           //copy constructor
ConcreteClassA& operator=(const ConcreteClassA &cc);  //assignment operator

//more methods....

//===========================================================================
ConcreteClassA.cpp

//destructor makes sure instances tracking counter is decremented
ConcreteClassA::~ConcreteClassA()
{
    this->decrementCount();
}

//only constructors and assignemnt operators call assign() method
ConcreteClassA::ConcreteClassA()
{
    //some other initialization...
    this->assignID();
}
//All other methods implementation left out for sensitivity of real estate...
4

2 回答 2

2

您必须考虑对象的副本。在 C++vector<T>::push_back()中,将对象的副本放入向量中。您在函数调用中创建的临时实例正在被销毁。这就是为什么“创建”计数高于“活动”计数的原因。

如果你真的想吝啬创建对象的实例,也许你应该将指针存储在向量中。这样你就必须明确地创建和销毁它们。

这是一篇关于类似内容的好帖子: https ://stackoverflow.com/a/1361227/2174

于 2012-02-08T21:43:35.680 回答
0
void IBase::decrementCount()
{
    -- this->count;
}

哇,我没有在那里检查运算符优先级,但我会写

void IBase::decrementCount()
{
    -- (this->count);
}

甚至没有三思而后行。(一个好的指导原则是,如果您有疑问或想要检查,您应该写得更清楚)。

而且,是的,那应该

void IBase::decrementCount()
{
    --count;
}
于 2012-02-08T21:59:01.667 回答