Argument type for Qt signal and slot, does const reference qualifiers matters?

后端 未结 2 976
自闭症患者
自闭症患者 2020-12-01 10:35

For signal and slot of below type

signals:
    void textChanged(const QString &);

public slots:
    void setText(const QString & text)
相关标签:
2条回答
  • 2020-12-01 11:13

    Disclaimer: My qt is rather rusty, but the signal/slot mechanism is still just C++ function calls. If the signal/slot mechanism actually copies objects into internal storage, my apologies (you'll need to check the Qt pages, there's a big one on signals/slots afaik) - as the bits below will only be relevant in a C++ context, not in a C++ + Qt context.

    If you leave out the reference, the string will be copied (and having the const would not matter, any changes made to it will remain in the function alone).
    If you leave in the reference but take out the const, you allow the method to modify the string that you give it. They both work, but do different things to the object you pass (amount of copying/possibility of retaining changes).

    I suggest you read the following resources:

    (on const correctness) https://isocpp.org/wiki/faq/const-correctness

    (on references) https://isocpp.org/wiki/faq/references

    to understand exactly what passing a parameter is and how void foo(const A&)/ void foo(const A)/ void foo(A&)/ void foo(A) are all different.

    0 讨论(0)
  • 2020-12-01 11:28

    Qt checks a normalized signature, meaning

    Normalization reduces whitespace to a minimum, moves 'const' to the front where appropriate, removes 'const' from value types and replaces const references with values.

    0 讨论(0)
提交回复
热议问题