Re: How to detect const reference to temporary issues at compile or runtime?
On 12/1/2010 04:07, Clinton Mead wrote:
Hi All
I've found recently that most of the errors in my C++ programs are of
a form like the 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;
};
In C++0x you could add the following deleted constructor
Y(const Z&&) = delete;
to prevent rvalues to bind to the first constructor.
class X
{
public:
X(const Y& y) : y(y) {}
Y y;
};
class Big
{
public:
Big()
{
for (int i = 0; i< 1000; ++i) { a[i] = i + 1000; }
}
int a[1000];
};
X get_x() { return X(Y(Z(123))); }
Given above mentioned deleted constructor, this line would not compile
any more.
int main()
{
X x = get_x();
Big b;
std::cout<< x.y.z.n<< std::endl;
}
OUTPUT: 1000
I would expect this program to output 123 (the value of x.y.z.n set in
get_x()) but the creation of "Big b" overwrites the temporary Z. As a
result, the reference to the temporary Z in the object Y is now
overwritten with Big b, and hence the output is not what I would
expect.
Yep, the behaviour of the program is undefined.
When I compiled this program with gcc 4.5 with the option "-Wall", it
gave no warning.
The fix is obviously to remove the reference from the member Z in the
class Y. However, often class Y is part of a library which I have not
developed (boost::fusion most recently), and in addition the situation
is much more complicated than this example I've given.
This there some sort of option to gcc, or any additional software that
would allow me to detect such issues preferably at compile time, but
even runtime would be better than nothing?
Others may help you in regard to compiler-specific options. My
suggestion is only a before-the-fact solution and would require that all
participants (including the library) are able to use such new language
features.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]