c++referenceobject-lifetimeconst-referencetemporaries

Prevent temporary from extending its lifetime?


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.


Solution

  • 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. Using shared_ptr and 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.

    #include <iostream>
    #include <string>
    #include <vector>
    #include <boost\shared_ptr.hpp>
    #include <boost\weak_ptr.hpp>
    
    using boost::shared_ptr;
    using boost::weak_ptr;
    
    using std::string;
    using std::cout;
    using std::endl;
    using std::vector;
    
    class person;
    typedef shared_ptr<person> Person;
    typedef weak_ptr<person> PersonWk;
    
    class person {    
        PersonWk pThis;
        friend Person makePerson(const string & nam, Person m = Person());
    
        string name;
        PersonWk mommy; // children should not affect parent lifetime, so store weak ptr
        vector<Person> children; // parents affect children lifetime so store child shared ptrs
    
        // make constructor private so that you can only make a person using factory method
        person(const string & nam, Person m) : name(nam), mommy(m) 
        { 
            // for demo purposes
            printf("creating %s\n", nam.c_str());
            ++personCount; 
        }
    
        // undefined copy constructor and assignment operators
        person(const person&);
        person& operator=(const person&);
    
    public:
        // for demo purposes
        static int personCount;
    
        ~person() 
        { 
            // for demo purposes
            printf("destroying %s\n", name.c_str());
            --personCount; 
        }
    
        Person baby(const string & nam){        
            Person child = makePerson(nam, Person(pThis));
            children.push_back(child);
            return child;
        }
    
        void talk() const{
            if (Person mom = mommy.lock()) 
                mom->talk();
            cout << name << endl;
        }
    };
    
    int person::personCount = 0;
    
    // factory method to make a person
    Person makePerson(const string & name, Person m) {
        Person p = Person(new person(name, m));
        p->pThis = p; // stash weak_ptr so I can use it to make a shared_ptr from "this" in the baby method
        return p;
    }
    
    void use(const Person p) {
        printf("In method use...\n");
        p->talk();
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        printf("personCount=%d\n", person::personCount);
        {
            Person ann = makePerson("Ann");
    
            // ann has baby and grandbaby, pass grandbaby to use method
            use(ann->baby("Susan")->baby("Wendy"));
    
            ann.reset(); // remove reference from root object. Destruction ensues...
        }
        printf("personCount=%d\n", person::personCount);
        return 0;
    }