This may be impossible, but I was wondering if it was possible to keep a temporary from ever lasting past its original expression. I have a chain of objects which point to parent objects, and a member function which will create a child object, a simplified example is here
class person{
string name;
person * mommy;
public:
person(const string & nam, person * m = 0) : name(nam), mommy(m) {}
person baby(const string & nam){
return person(nam, this);
}
void talk() const{
if (mommy) mommy->talk();
cout << name << endl;
}
};
int main(){
person("Ann").baby("Susan").baby("Wendy").talk(); // fine
const person & babygirl = person("Julie").baby("Laura"); // not fine
babygirl.talk(); // segfault
return 0;
}
The way I want to use person is to pass it to a function, and something like this:
void use(const person & p) {
p.talk();
}
use(person("Anna").baby("Lisa"));
Is fine.
This will work fine as long as none of the temporaries survive past the original expression, but if I bind one of the final temporaries to a const reference, its parents don't survive, and I get a segfault. I can hide person's copy constructor and assignment operator, but is there any way I can prevent this kind of error from happening? I'd like to avoid dynamic allocation if possible.
It looks like you are creating a data structure here where children have pointers to their parents. Using temporaries is guaranteed to cause you grief in this case. In order to make this safe, you will need to dynamically allocate and possibly use some sort of reference counting.
Have you considered using
boost::shared_ptr? It is an implementation of a reference counted smart pointer class. Usingshared_ptrand perhaps some factory methods, you might be able to get the effect you want and reduce the pain of dynamic memory allocation. I tried it out and it seems to work. Once the code exits the scope, the objects are all destroyed because there are no references left to the shared_ptrs.Edit: In response to zounds' comment, I have modified the example so that the root object controls the data structure's lifetime.