0

Hopefully this isn't too stupid but I want to make sure I'm doing this right.

Some Qt functions return Qt objects as values, but we may want to store them in a pointer somewhere. For example, in QDomDocument, the function documentElement returns a QDomElement, not a pointer to it. Now, as a member of my class I have:

QDomElement *listRootElement;

In a function that sets things up I am using this:

listRootElement = new QDomElement;
*listRootElement = mainIndex->documentElement();

(mainIndex is a QDomDocument.)

This seems to work, but I just want to make sure I'm doing it right and that nothing will come back to bite me.

It would be very similar for some of the image functions where a QPixmap might be returned, and I want to maintain pointers to QPixMap's.

Thanks for any comments!

Micah Yoder
  • 695
  • 1
  • 5
  • 8
  • A bit more to it - it seems a bit of a waste to construct an empty element. And worse, what if it is a class with no default constructor? – Micah Yoder Oct 12 '10 at 10:49

3 Answers3

0

Assuming that you want to store a pointer to a QDomElement for some reason, and assuming that you aware of the potential pitfalls with pointers (like, two pointers might point to the same object):

The only thing to keep in mind is that the popular 'parent takes care of deleting children' system which Qt uses is only available for QObject (sub-)classes. So when new'ing a QString or a QDomElement or something like that, keep in mind that you do have to delete it yourself, too.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
0

I'm guessing, but I think this:

listRootElement = new QDomElement(mainIndex->documentElement());

...may allow the compiler to optimise better (see this question for some reasoning).

Community
  • 1
  • 1
sje397
  • 41,293
  • 8
  • 87
  • 103
  • Ok. I *do* want to be able to edit the DOM and save it from elsewhere in the program. Is there a way to do this without creating the copy? – Micah Yoder Oct 12 '10 at 11:07
  • @Micah - I think I'm wrong about that. Usually, changing a copy doesn't affect the original - but these are just wrappers around an internal structure that *is* modified using the object's methods. – sje397 Oct 12 '10 at 11:29
0

You're overwriting the initially allocated object:

QDomElement *listRootElement; // undefined ptr value, I'd prefer null or new right away
listRootElement = new QDomElement;
*listRootElement = mainIndex->documentElement();

You're essentially doing:

int *x = new int(42);
*x = 47;

This works because both QDomElement and int implements the assignment operator (=).

Note that there's no need to delete anything, as the returned temporary is copied into your newly allocated object.

Macke
  • 24,812
  • 7
  • 82
  • 118