ternary operator and temporaries
Hi
I've been having some problems with come Qt code (not mine!) that looks like this:
#include <qstring.h>
#include <iostream>
using namespace::std;
static QString bar;
#define REL_PATH_TO_ROOT "../../"
QCString func()
{
QCString result;
if (1)
{
return REL_PATH_TO_ROOT;
}
return result;
}
int main()
{
bar = true ? func() : QString("");
cout << "bar is " << bar << endl;
}
The crux of the problem seems to be in the line
bar = true ? func() : QString("");
[QString is a reference counted string class, QCString is a wrapper around char*]
Here's my impression of what is going on:
A temporary (of type QCString) is created at the end of func(), and used to create a second temporary (of type QString) using its conversion constructor. The 1st temporary then gets destroyed. The QString assignment operator then gets called, and increases the refcount of the 2nd temporary to 2, clears its own data, and sets the data pointer to point to that of the 2nd temporary.
The 2nd temporary then goes out of scope and the refcount of bar goes down to 1.
That's the theory. In practice, I'm seeing corruption of bar's data.
QString does have an assignment operator from QCString. I'm wondering if the ternary operator is causing side effects, since it's being used in an expression like
type A = bool ? type B : type A;
Is there an implicit conversion from type B to type A so that the result of the sub-expression 'type B : type A' has just one type? If so, what is the lifetime of the temporary used to bring about that implicit cast?
A+
Paul