Qt correct unowned QObject return semantic

71 Views Asked by At

I have a QObject SystemdDBusManager that can return other QObjects (Unit class). Those objects do not have any reason to be owned by SystemdDBusManager, but according to the Qt documentation, this can imply that the returned object is owned by SystemdDBusManager.

class SystemdDBusManager : public QObject
{
Q_OBJECT

public:
    Unit *getUnit(QString const &name);    
};

What would be a good way to make it clear that the Unit is not owned by SystemdDBusManager?

2

There are 2 best solutions below

0
On BEST ANSWER

You can return a shared pointer or a unique pointer to the Unit object, depending on how you are going to use the object.

That way, the caller will not have to care about the lifetime of the pointer.

4
On

Write Documentation.

There is no hard rule, who owns a pointer, it's all convention. If you want the caller to take ownership, you have to make it clear in the documentation of your function.

It may also be a good idea to convey this intent in the function name, so instead of getUnit I'd suggest naming it takeUnit which implies taking ownership from SystemDBusManager.