Ok... I'm getting the hang of this, I think. However, I've hit a small obstacle and need help passing over it.
For now I'm skipping Bubba's excellent suggestions. I prefer to have my own code doing the pointer management, as your post above so clearly exemplified Bubba.. But I'm trying this with baby steps, so I figured that for the next few revisions of my code I'll use the boost libraries, untill I find myself comfortable enough to start coding my own manager class.
Ok... anyways... this is the problem:
A cutdown version of my CItem class just to put those typedefs into context for you good people:
Code:
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
class CItem {
public:
typedef boost::shared_ptr<CItem> CItem_Ptr;
typedef boost::weak_ptr<CItem> CItem_wPtr;
};
A cutdown version of my CContainer class:
Code:
class CContainer : public CItem {
public:
CContainer() {};
virtual ~CContainer() {};
CContainer& add(CItem_Ptr);
CContainer& remove(CItem_Ptr);
private:
std::vector<CItem_wPtr> contents_;
};
And this is where I'm having problems; In the definition of add() when checking for duplicated entries (colored red):
Code:
CContainer& CContainer::add(CItem_Ptr obj) {
CItem_wPtr ptr(obj); //creating weak_ptr
if(obj.get() == this)
throw std::invalid_argument("inserting container inside itself attempt");
if( find(contents_.begin(), contents_.end(), ptr) != contents_.end() )
throw std::invalid_argument("duplicate item attempt in inventory");
if( !obj->isWearable(Container) ) {
std::cerr << '\n' << "Object cannot be placed inside a container." << '\n';
return *this;
}
if( obj->weight() > (int)maxweight_ || obj->volume() > (int)maxvol_ ) {
std::cerr << '\n' << "Object is too big for this container." << '\n';
return *this;
}
int currweight = (int)maxweight_ - this->weight();
int currvol = (int)maxvol_ - this->volume();
if( obj->weight() > currweight || obj->volume() > currvol ) {
std::cerr << '\n' << "Container is too full." << '\n';
return *this;
}
// ok to add
//weight( weight() + obj->weight() );
//volume( volume() + obj->volume() );
//contents_.push_back(ptr);
return *this;
}
I've got to the point where I understood boost::weak_ptr doesn't provide a equality operator overload. However, a predicate function or a function class for the find algorithm will not work either because what i'm searching for is any attempt to duplicate an object instance inside the container.
As in:
Code:
int main() {
CItem::CItem_Ptr armor(new CArmor);
armor->load("A001");
CItem::CItem_Ptr armor2(new CArmor);
armor2->load("A001");
CContainer container;
container.load("C001");
container.add(armor);
container.add(armor); // Illegal. Would allow for items duplication
container.add(armor2); //Valid. Just another instance of the same object (2 helms +1)
}