views:

488

answers:

2

Hey all,

ok, so I got a doubt, I want to know if this is possible:

I'm using a database, with generic data (strings, ints, bools, etc...). Whenever an object is constructed or a member of an object is modified, I have to query the database with the specific action (SELECT or UPDATE). First of all, this isn't a DB related question, my real problem is that I have a ptr_vector which holds boost::any's pointers to members of the object. In code something like this:

class Enemy{
  private:
    //some private data...
  public:
    auto_ptr<int> ID_Enemy;
    auto_ptr<string> Enemy_Name;
    //miscellaneous methods...
};

then I pass the members I want to modify to a function of another miscellaneous class which takes as argument a boost::any*:

misc_class.addValues((boost::any*)(ID_Enemy.get()));
misc_class.addValues((boost::any*)(Enemy_Name.get()));

that same class accepts the any*, and does the following:

auto_ptr<boost::any> val2(val); //being val, the passed any*
Enemy_Values.push_back(val2);

Enemy_Values is a ptr_vector. So when I access this misc_class which has Enemy_Values as member, I want to change the value to which an auto_ptr inside is pointing:

misc_class.Enemy_Values[0] = (boost::any)(69);

And here, I get a violation error. I've tried many things, and someone told me that I shouldn't be using containers of auto_ptr or converting back and forth with boost::any. Is this that I am doing possible, or there is a better and more intuitive way?

Thanks in advance.

+1  A: 

(boost::any*)(ID_Enemy.get()) performs a reinterpret_cast since you are casting unrelated pointer types. This means you get an invalid pointer to an any, pointing to what is really an integer. Instead, construct a temporary boost::any object and pass it by reference to addValues:

misc_class.addValues(boost::any(ID_Enemy.get());

Your use of auto_ptr is in fact incorrect: auto_ptr deletes objects on the freestore but here we're dealing with locals instead. addValues merely needs to push the value of the any object into the vector:

Enemy_Values.push_back(val);

... and Enemy_Values should just be a std::vector.

You could do this with a ptr_vector and freestore-allocated boost::any objects, but that would be more complicated than necessary.

A: 

auto_ptr has a number of problems. Since you are already using boost, why not use boost::shared_ptr instead?

Skrymsli