c++ - How to detect const reference to temporary issues at compile or runtime? -
i've found of errors in c++ programs of form following example:
#include <iostream> class z { public: z(int n) : n(n) {} int n; }; class y { public: y(const z& z) : z(z) {} const z& z; }; class x { public: x(const y& y) : y(y) {} y y; }; class big { public: big() { (int = 0; < 1000; ++i) { a[i] = + 1000; } } int a[1000]; }; x get_x() { return x(y(z(123))); } int main() { x x = get_x(); big b; std::cout << x.y.z.n << std::endl; }
output: 1000
i expect program output 123 (the value of x.y.z.n set in get_x()) creation of "big b" overwrites temporary z. result, reference temporary z in object y overwritten big b, , hence output not expect.
when compiled program gcc 4.5 option "-wall", gave no warning.
the fix remove reference member z in class y. however, class y part of library have not developed (boost::fusion recently), , in addition situation more complicated example i've given.
this there sort of option gcc, or additional software allow me detect such issues preferably @ compile time, runtime better nothing?
thanks,
clinton
i submitted such cases on clang-dev mailing list few months ago, no 1 had time work on (and neither did i, unfortunately).
argyrios kyrtzidis working on though, , here last update on matter (30 nov 23h04 gmt):
i reverted previous commit, better fix in http://lists.cs.uiuc.edu/pipermail/cfe-commits/week-of-mon-20101129/036875.html. e.g. for
struct s { int x; }; int &get_ref() { s s; s &s2 = s; int &x2 = s2.x; return x2; }
we get
t3.cpp:9:10: warning: reference stack memory associated local variable 's' returned return x2; ^~ t3.cpp:8:8: note: binding reference variable 'x2' here int &x2 = s2.x; ^ ~~ t3.cpp:7:6: note: binding reference variable 's2' here s &s2 = s; ^ ~ 1 warning generated.
the previous attempt failed self-hosting test, hope attempt pass. i'm pretty glad argyrios looking anyway :)
it isn't perfect yet, admittedly, it's quite complicated problem tackle (reminds me of pointer aliasing in way), nonetheless great step in right direction.
could test code against version of clang ? i'm pretty sure argyrios appreciate feedback (whether detected or not).
Comments
Post a Comment