C++ Add this pointer to a container by calling it in base class constructor
class Base
{
public:
Base (int a, int b);
private:
int a,b;
};
class Derived1
{
public:
Derived1():base(1,2){}
};
similarly Derived2, Derived 3 which doesnt contain any data members on its own
Now i need to contain these derived objects in a singleton, so i was thinking to call this in base constructor like
Base::Base(int a, int b)
{
CBaseMgr::GetInstance()->AddtoVector(this);
}
so now if i construct
Derived d1, d2, d3 etc. will the Singleton's container contain all derived objects?
My doubt is can i do this adding of objects to container in base ctor or should i 开发者_运维技巧do in derived ctor.?
If all the derived class call this base class constructor, yes, you should be fine.
Just beware of the copy constructor which, if not overloaded, will not add this
to your global vector.
I suppose you want as well remove the instances that were destroyed, from the global vector ?
If so, don't forget to declare Base::~Base
to be virtual
, so that he gets called by derived classes.
Doing this in Base's constructor should be fine, as long as you're not dereferencing this
before the whole construction is done.
My doubt is can i do this adding of objects to container in base ctor or should i do in derived ctor.?
You can safely do it in the base constructor but you have to take care of the following:
explicitely declare copy constructor semantics (if you want objects to be copy-constructible, fine; if not, declare the base copy constructor as private, and do not implement it, or make Base inherit privately from
boost::noncopiable
).store Base references as pointers (I guess you already know this).
declare base's destructors virtual (and have them remove the instance from the manager)
make sure the removal process doesn't throw any exceptions ( throwing exceptions in destruction may lead to transforming the Earth into a singularity or other undefined behaviour :) ).
精彩评论