[Development] Setters: Clarifying the ownership
annulen at yandex.ru
Fri Jan 19 16:42:23 CET 2018
19.01.2018, 18:16, "Jesus Fernandez" <jesus.fernandez at qt.io>:
> Hi all!
> I always found something annoying in the Qt API. The problem comes with the setters of our properties. When I want to pass an object to a property I never know if I need to take care of the object or relay on parenting system to avoid memory leaks.
> To know if the object is going to be reparented, I open the assistant and look for the setter to try to find the famous "takes ownership of" in the function description.
> Mårten Nordheim and I were talking about possible solutions to this problem. Typical things came to the discussion:
> - adding a macro like Q_TAKES_OWNERSHIP to the function that expands to nothing
> - wrapping the parameters with a template class (gsl::owner<T>)
> - ...
> After some discussion he came with the idea of add a different "verb" to the setter, replace "set" with "give". So when we are giving the ownership of an object to instead of setSomething(&object); we will write giveSomething(&object); I really like this solution, it will improve a lot the readability of the client (and internal) code.
> For example: QCoreApplication::setEventDispatcher will be QCoreApplication::giveEventDispatcher.
> Of course at the beginning this will be a new function and the old set* functions will be kept, but marked as deprecated.
FWIW, as we are talking about API changes, I pretty much like modern WebKit's conventions:
1. When function takes ownership on object, argument type is T&& or std::unique_ptr<T>&&
2. When function is a factory and gives up ownership, it returns std::unique_ptr<T>
3. When function needs to modify object, but doesn't take ownership, it uses T* is pointer can be nullptr, and T& otherwise
The latter item contradicts Qt's tradition of avoiding references, but I found it very convenient, at least inside implementation. It allowed to get rid of many excessive null checks inside QtWebKit code and fix some missing null checks.
> Best regards,
> Development mailing list
> Development at qt-project.org
More information about the Development