I was surprised to discover that passing a reference to a temp that is clearly
going out of scope is not tracked at all. While in general catching a pointer
to a value with shorter lifetime could be hard, if it's auto, it's fairly
obvious.In the following example, the commented out code correctly gives a
warning, but the second does not, even though the semantics are exactly the
same. This came up because I accidentally passed a value into an object by
value, but stored it by reference, which is shown second.

Example:

#if 0
int* foo(int a) {
  int x = 2 + a;
  return &x;
}
#endif

int* foo(int a) {
  int x = 2 + a;
  int* p = &x;
  return p;
}

int main() {
  foo(3);
}


2. class-based accidental pass by value.

class Foo {
private:
  int& x;
public:
  Foo(int x_) : x(x_) {} // THIS IS WRONG!
};


-- 
           Summary: no warnings for passing temps by reference into
                    obviously longer lifetime pointer
           Product: gcc
           Version: 4.0.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: dkruger at stevens dot edu
  GCC host triplet: i686-linux


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31788

Reply via email to