C++ constant reference lifetime (container adaptor)

前端 未结 5 1450
花落未央
花落未央 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:28

    Temporary const references only have the lifetime of the current statement (that is, they go out of scope just before the semi-colon). So the rule of thumb is never rely on a const-reference existing beyond the lifetime of the function that receives it as a parameter, in this case that's just the constructor. So once the constructor is done, don't rely on any const references to still be around.

    There is no way to change/override/extend this lifetime for temporaries. If you want a longer lifetime, use an actual object and not a temporary:

    adapter a, b; 
    container(a, b); // lifetime is the lifetime of a and b
    

    Or better yet, just don't use constant references to class members except in the most dire circumstances when the objects are very closely related and definitely not temporary.

提交回复
热议问题