Skip to Main Content

DevOps, CI/CD and Automation

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ternary operator and temporaries

paul_floydJul 11 2005 — edited Jul 13 2005
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 10 2005
Added on Jul 11 2005
6 comments
193 views