I need the flexibility of being able to change parameters passed around to different functions, depending from where the call to the function happened, so I decided I’d put all my parameters in a struct, however most of these parameters are structs or classes themselves and I want to have the option of leaving them NULL, so I have to pass pointers to the structs/classes.
struct A
{
otherB* b; // NULL should be a valid value
otherC* c;
};
However my question is now, passing A around these pointers will be the only thing copied, so if I did the following there would be a problem right?
void func(A& a) //non const cause I wanna change contents of A.
{
a.b = new b();
}
A myA;
otherC somec; // all these are currently automatic variables in my pgm.
myA.c = &somec;
func(myA); //myA goes out of scope? so I've lost all pointers assigned and since somec is out of scope too, I have a problem?
What would the best way to resolve something like this+ I want the flexibility of being able to pass NULL to any of my parameters, however not sure if using raw pointers everywhere is a good idea?
To solve the problem of resource management, you should use
boost::shared_ptr(orstd::shared_ptrin C++0x).When
myAgoes out of scope, all resources are deallocated automatically. Sincesomecwas allocated on the stack, we wrapped it in ashared_ptrthat uses anull_deleter, that could look like this:This will not delete the object, it will do nothing (which is just what we want for stack-allocated objects). Keep in mind however, that you have to make sure that
someclives longer thanmyA, otherwise you will get access violations.