Will the reference count still work if storing std::weak_ptr
with static_pointer_cast
?
Here is a very simplifed example (note that the SmallBox
and BigBox
classes are almost exactly the same):
#define OWNER_SMALLBOX 1
#define OWNER_BIGBOX 2
class Object
{
private:
std::weak_ptr<void> owner;
int ownerType;
public:
void doSomethingIfOwnerStillExist()
{
if(std::shared_ptr<void> ownerShared = owner.lock())
{
switch(ownerType)
{
case OWNER_SMALLBOX:
std::shared_ptr<SmallBox> smallBox = std::static_pointer_cast<SmallBox>(ownerShared);
break;
case OWNER_BIGBOX:
std::shared_ptr<BigBox> bigBox = std::static_pointer_cast<BigBox>(ownerShared);
break;
}//switch
}
}
Object(std::shared_ptr<void> _owner, int _ownerType)
{
owner = _owner;
ownerType = _ownerType;
}
};
class SmallBox
{
private:
std::list< std::shared_ptr<Object> > objects;
public:
static void addObject(std::shared_ptr<SmallBox> _smallBox)
{
std::shared_ptr<void> owner = std::static_pointer_cast<void>(_smallBox);
objects.push_back(std::make_shared<Object>(owner, OWNER_SMALL_BOX));
}
};
class BigBox
{
private:
std::list< std::shared_ptr<Object> > objects;
public:
static void addObject(std::shared_ptr<BigBox> _bigBox)
{
std::shared_ptr<void> owner = std::static_pointer_cast<void>(_bigBox);
objects.push_back(std::make_shared<Object>(owner, OWNER_BIGBOX));
}
};
I know I can make the SmallBox
and BigBox
classes inherit from i.e. a GeneralBox
class, and have the void
type replaced with a GeneralBox
type, but the weak_ptr
can point to several other types aswell, making inheritance quite big and clumpsy.
I am curious if the shared_ptr
still can keep track of the weak pointers converted to void.