C++ constant reference lifetime (container adaptor)

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

    Don't do this. A temporary is destroyed immediately after the expression in which it was created (except in the case that it's immediately bound to a reference, in which case it's the scope of the reference). The lifetime cannot be extended to that of the class.

    This is why I never store members as references - only copied objects or pointers. To me, pointers make it obvious that the lifetime comes in to play. Especially in the case of a constructor, it's non-obvious that your constructor params must outlive the class itself.

提交回复
热议问题