Passing Qt classes by const reference
Asked Answered
W

2

7

It's known that Qt classes use copy-on-wite when passing by value. So copy isn't done until its needed. I have seen many times passing Qt classes by const reference when only needed read-only access to object. Why do people pass const QString& instead of simple QString if in both cases no copy is done?

Wold answered 12/6, 2013 at 17:20 Comment(0)
P
12

This is because magic comes with a price. QString doesn't copy entire string, but it calculates references. Many copyings of QString can slow down the program. If const QString& is sufficient for your needs, why not use it? It is still faster.

Physical answered 12/6, 2013 at 17:27 Comment(0)
B
8

Copy on write does not mean, that object will not be copied. It only means that deep copy will be made on write, i.e. actual data will be copied on write. Main complexity of making a copy is of course in that data copying. But just making a shallow copy involves some operations, like reference counting.

In result, passing by reference is still cheaper, than making shallow copy.

Bit answered 12/6, 2013 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.