[Development] RFC: RAII for property changes

Keith Gardner kreios4004 at gmail.com
Wed Apr 15 21:29:02 CEST 2015


On Wed, Apr 15, 2015 at 2:20 PM Andre Somers <andre at familiesomers.nl> wrote:

> On 15-4-2015 21:05, Keith Gardner wrote:
>
>  >   QPropertyGuard g{this};
>> >   g.addProperty("a"); // use QObject::property
>> >   g.addProperty("b", m_b); // take value member by reference
>> >   g.addProperty(m_c, &cChanged); // ...and also slot address
>>
>> There's type erasure going on, so it will allocate memory. Allocating
>> memory
>> in a setter that might just change an int is what I call inefficient.
>>
>
>  Would something like this be better?
>
>  // constructor
> // Provide an initial value and a std::function to notify about the change
> Property<bool> m_example = Property<bool>(false, [&](bool value){
>     emit exampleChanged(value);
> });
>
>  // getter
> bool *::example() const {
>     return m_example;
> }
>
>  // setter
> void *::setExample(bool value) {
>     m_example = value;
> }
>
>  The working code for this example can be found
> https://github.com/kreios4004/Property_Class.
>
>  Thank you for posting that.
>
> I took a look at it, but I am not sure it actually solves much. It moves
> the check if something changed to the wrapped variable, but it makes using
> that value then more complicated. Instead of using the variable directly,
> one now has to go through m_example.getValue() everywhere.
>

This is partially true.  If it is containing a class or a struct, then you
are correct.  If it is an int or float and you want to perform some math
operation with it, it has the operator const T&() to perform the get
automatically.


> Not pretty, I think. The case of modifying more than one property in one
> go is also not solved. On the one hand, dependent properties (such a
> isValid property) are not updated unless you manually write that code
> again, and on the other hand if you use this to set more than one property
> in a method, you still are sending signals at the point the class is in an
> inconsistent state.
>

True.  My goal was to perform a type safe way of change detection so I
wouldn't have to write the boilerplate code over and over.  It also
provides a way customize the way the signal is called in the callback.  It
does suffer in the more complex scenarios when more than one operation is
happening to the object.


> One nice side effect of my implementation is that the notification is
> actually only send once. Even if the property value is changed multiple
> times in the meantime, you still get only one notification. That can be
> very convenient, even if you don't use it much.
>

This is very appealing.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20150415/91dff45c/attachment.html>


More information about the Development mailing list