Question

I have a function which creates an object QMenu (in heap)

QMenu* createMenu(QWidget* parent); // parent will takes ownership of the menu

The function will never return a null pointer. But I think the declaration don't tell the point because it returns a pointer. Thus when using the method, I need

if (QMenu* m = createMenu(parent))
    m->...

which is annoying. If it returns a reference, it tells the point.

QMenu& createA(QWidget* parent);

I never see code declares this way. Is this okay? Is there any better declaration for the point?

Was it helpful?

Solution 2

Yes, it's fine to return a created object by reference, if the function makes its own arrangements for ownership of that object's lifetime.

One big example of a function that does this: V& std::map<K,V>::operator[](const K&);.

OTHER TIPS

Just document that it doesn't return null. Not exactly very high-tech as a solution, but you'll see that it works great in practice.

Since it's then clear that your function doesn't return null, you don't have to write:

if (QMenu* m = createMenu(parent))
    m->...

You just write:

QMenu* m = createMenu(parent);
m->...

Think about it: either you need the if check in some form -- but then it's not true that the function never returns null.

Or the function really never, ever returns null. Then the if check is useless.

That being said, you can still add an assertion there to be extra safe:

QMenu* m = createMenu(parent);
assert(m != nullptr); // if you use C++11; otherwise assert(m != 0);
m->...

This means as much as "If m is null, then my own code is messed up and the program is wrong. If that happens, please quit the program ASAP!"

The simplest and clearest way would be to return a value:

A createA();

Usually, if you need to allocate resources on "the heap", a good strategy is to design A such that it handles those resources itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top