开发者

C++ - Where to store a global counter?

The diagram http://www.freeimagehosting.net/uploads/2fd3f4161c.png

Here's the Minimalist-UML diagram of an app I've been working on. It's supposed to simulate the management of a bunch of sensors relating to different measurements. Please ignore the House class, the diagram is outdated...

However, I have trouble. Each sensor (sound, contact, heat, pressure, gas - All of these inherit from sensor) has an unique ID, starting at 0 for the first one and ending at the total number of sensors - 1.

For good p开发者_如何学运维ractices' sake, where shall I store the total number of sensors, so the classes I'm using for input/output of files (saving and loading) and insertion of new sensors can access and increment that counter?

Thank you for your time!


One option would be to create a static function in your Sensor class that increments and returns a static counter variable. The constructor for Sensor could call this function to get an ID.

// header file
class Sensor
{
...
protected:
   static int getId() { return id++; }
private:
   static int id;
   int myId;
};

// .cpp file
int Sensor::id = 0;

Sensor::Sensor(...)
: myId(getId())
  ...
{}

I'm ignoring threading and persistence issues here. But hopefully this gives you a better idea.


Whatever object creates the sensors should assign the identifiers to the sensors.

If multiple objects create sensors, then they should be assigned a pointer or reference to a provider of identifiers when they are created and they should query that provider for a new unique identifier as they create new sensor objects.


Your unique ID, like a database table ID will likely have some issues.

You will probably find, eventually, that your ID needs to persist across sessions--that your window's ID is used in some other relationship.

You may, some day, also find that it needs to be unique across multiple server/client sets.

I'm just suggesting that you should consider these issues off the bat.

As for where the ID should be generated, since all your "Sensor" classes inherit from one base class, I think I'd generate it via a threadsafe method in that base class--and I'd store it there as well.


what's the problem? do you use a Vector to store your sensors? define a Vector of holding sensor-objects in the house.

can access and increment that counter

you don't have to do this, the Vector does it for you


Have a look at the Singleton pattern assuming you don't want to do it with a database of some sort.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜