我正在实现一个引用计数基类,并且希望为每个正在创建的继承该接口的对象设置uniqe数。
这是该类的代码片段:
HEADER:
class Object
{
const long long int object_id;
public:
Object();
virtual ~Object();
};
CPP:
Object::Object() : object_id(reinterpret_cast<long long int>(&object_id))
{
}
如果这是安全的方法我是否认真,如果不是,为什么不呢? 我没有使用rand和srand函数,原因有两个:
编辑: 在哪一点上创建了成员object_id?在构造函数内部或外部(在初始化列表之前或之后)hm hm? 非常感谢!
答案 0 :(得分:3)
这不是一种安全的方法。您没有考虑过非虚拟多重继承。这很少见,但很合法。
class A : public Object {};
class B : public Object {};
class C : public A, public B {}; // Now C has *two* IDs!
答案 1 :(得分:1)
好的,这是我第一次回答我自己的问题,但这就是我做的独特工作。
//this is base class which only hold the id and may be inherited only by Object class
struct object_id
{
//friend class Object;
//protected: MAKE IT PUBLIC FOR TESTING PURPOSES! FOR NOW
int id;
object_id() : id(reinterpret_cast<int>(&id)) { } //id will be 100% uniqe
};
//this class inherits virtualy so the id member will be in each derived class only once!
class Object : virtual public object_id //INHERIT PRIVATE LATER, now it's public for testing!
{
public:
Object(){}
virtual ~Object(){}
};
TEST:
//now let's make some diamod inheritance to se if it work:)
class a: public Object{};
class b: public Object{};
class c: public a,b{};
//now let's test it:
int main()
{
c obj;
c ss;
c dd;
cout << endl << obj.id << endl << ss.id << endl << dd.id << endl;
cin.ignore();
return 0;
}
这很好用,现在每个对象都有自己唯一的ID!