C++ constant reference lifetime (container adaptor)

前端 未结 5 1413
花落未央
花落未央 2020-11-28 12:54

I have code that looks like this:

class T {};

class container {
 const T &first, T &second;
 container(const T&first, const T & second);
};
         


        
5条回答
  •  迷失自我
    2020-11-28 13:31

    The reference will exist for the entire lifetime of container, but the object being referenced will exist only for the lifetime of that object. In this case, you have bound your reference to a temporary object with automatic storage allocation ("stack allocation", if you will, although that isn't C++ nomenclature). Therefore, you cannot expect the temporary to exist beyond the statement in which it was written (as it goes out of scope immediately after the call to the constructor for container). The best way to deal with this is to use a copy, instead of a reference. Since you are using a const reference, anyway, it will have similar semantics.

    You should redefine your class as:

    template 
    class container 
    {
        public:
            container(const T& first, const T& second) : first(first), second(second) {}
        private:
            const T first;
            const T second;
    };
    

    Alternatively, you could give your objects a name to prevent them from going out of scope:

       adaptor first;
       adaptor second;
       container c(first,second);
    

    However, I don't think this a good idea, since a statement such as return c is invalid.

    Edit
    If your goal is to share objects in order to avoid the cost of copying, then you should consider using smart pointer objects. For example, we can redefine your object using smart pointers as follows:

    template 
    class container 
    {
        public:
            container(const boost::shared_ptr& first, const boost::shared_ptr& second) : first(first), second(second) {}
        private:
            boost::shared_ptr first;
            boost::shared_ptr second;
    };
    

    You can then use:

    boost::shared_ptr first(new adaptor);
    boost::shared_ptr second(new adaptor);
    container c(first,second);
    

    Or, if you want to have mutable copies of first and second locally:

    boost::shared_ptr first(new adaptor);
    boost::shared_ptr second(new adaptor);
    container c(boost::const_pointer_cast(first),boost::const_pointer_cast(second));
    

提交回复
热议问题