C++ catching dangling reference

前端 未结 7 848
温柔的废话
温柔的废话 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:28

    I think this is not possible to catch all these, although some compilers may give warnings in some cases.

    It's as well to remember that references are really pointers under the hood, and many of the shoot-self-in-foot scenarios possible with pointers are still possible..

    To clarify what I mean about "pointers under the hood", take the following two classes. One uses references, the other pointers.

    class Ref
    {
      int &ref;
    public:
      Ref(int &r) : ref(r) {};
      int get() { return ref; };
    };
    
    class Ptr
    {
      int *ptr;
    public:
      Ptr(int *p) : ptr(p) {};
      int get() { return *ptr; };
    };
    

    Now, compare at the generated code for the two.

    @@Ref@$bctr$qri proc    near  // Ref::Ref(int &ref)
        push      ebp
        mov       ebp,esp
        mov       eax,dword ptr [ebp+8]
        mov       edx,dword ptr [ebp+12]
        mov       dword ptr [eax],edx
        pop       ebp
        ret 
    
    @@Ptr@$bctr$qpi proc    near  // Ptr::Ptr(int *ptr)
        push      ebp
        mov       ebp,esp
        mov       eax,dword ptr [ebp+8]
        mov       edx,dword ptr [ebp+12]
        mov       dword ptr [eax],edx
        pop       ebp
        ret 
    
    @@Ref@get$qv    proc    near // int Ref:get()
        push      ebp
        mov       ebp,esp
        mov       eax,dword ptr [ebp+8]
        mov       eax,dword ptr [eax]
        mov       eax,dword ptr [eax]
        pop       ebp
        ret 
    
    @@Ptr@get$qv    proc    near // int Ptr::get()
        push      ebp
        mov       ebp,esp
        mov       eax,dword ptr [ebp+8]
        mov       eax,dword ptr [eax]
        mov       eax,dword ptr [eax]
        pop       ebp
        ret 
    

    Spot the difference? There isn't any.

提交回复
热议问题