开发者

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

开发者 https://www.devze.com 2022-12-14 22:53 出处:网络
For signal and slot of below type signals: void textChanged(const QString &); public slots: void setText(const QString & text)

For signal and slot of below type

signals:
    void textChanged(const QString &);

public slots:
    void setText(const QString & text)

the type of argument of textChanged and setText seems to work invarable of const and &. Does the constant and reference qualification make any difference compared to just using QString ?

QObject::connect(a,SIGNAL(textChanged(QString)),b,SLOT(setText(QString)));
QObject::connect(a,SIGNAL(textChanged(const QString &)),b,SLOT(setText(const QString &)));

EDIT: I did not notic开发者_C百科e the output window showing error messages when there is incompatible type being used in SIGNAL or SLOT. I thought the signal slot mechanism is capable of detecting argument type error at compile time.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号