C++逻辑错误:试图为创建的所有实例生成唯一的ObjectID,计数器注册错误

C++ Logic Bug: Trying to Generate Unique ObjectIDs for all Instances Created, Counter Registering Incorrectly

本文关键字:错误 实例 唯一 ObjectID 注册 计数器 C++ 创建      更新时间:2023-10-16

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

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

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

我的输出是:

objID = 5, and count = 2

预期结果:

objID = 2, and count = 2

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

请告知。

//===========================================================================   
//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...

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

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

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

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

哇,我还没有检查操作员的优先级,但我会写

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

甚至不假思索。(一个好的指导原则是,如果你有疑问或想检查,你应该写得更清楚)。

是的,应该只是

void IBase::decrementCount()
{
    --count;
}
相关文章: