C++ catching dangling reference

前端 未结 7 819
温柔的废话
温柔的废话 2020-12-14 22:02

Suppose the following piece of code

struct S {
    S(int & value): value_(value) {}
    int & value_;
};

S function() {
    int value = 0;
    retur         


        
7条回答
  •  攒了一身酷
    2020-12-14 22:25

    There is a guideline I follow after having been beaten by this exact thing:

    When a class has a reference member (or a pointer to something that can have a lifetime you don't control), make the object non-copyable.

    This way, you reduce the chances of escaping the scope with a dangling reference.

提交回复
热议问题