hi,
recently i discovered a memory leak in our code; after some investigation i
could reduce it to the following problem:
return objects of functions are handled as temporary objects, hence their
dtor is called immediately and not at the end of the function. to be able to
use return objects (to avoid copying) i often assign them to a const
reference.
now, casting a const return object from a function to a non-const reference
to this return object calls immediately the dtor of the return object
anyway, any further operation deals with a non-valid object then. if i do
this in two steps - first holding a const reference to the return object and
then const_casting it, everything works like i expected it.
does anybody know whether the compiler behaves correctly?
i use the following short example to illustrate my question:
const string getastring()
{
return string();
}
void funcWmemleak()
{
string& str = const_cast<string&>(getastring());
str = "test"; // this is already an invalid object because the dtor was
called before (and won't ever be called again of course)
}
void funcWOmemleak()
{
const string& str1 = getastring();
string& str = const_cast<string&>(str1);
str = "test";
}
int main()
{
funcWmemleak();
funcWOmemleak();
}
--
klaus triendl