4

Is there a rationale why the + operator taking a QString returns const QString instead of QString?

This is different to the + operator for std::basic_string.

I assume this choice for QString was made delibrately and is probably documented somewhere, but I couldn't find this kind of information.

fabian
  • 80,457
  • 12
  • 86
  • 114
  • Btw: This came up when trying to work with move semantics and `QString`. Basically I wonder why a `QString` cannot be move-constructed from the result of the expression `(qstring1 + ...)`. This question isn't looking for solution/workaround for this problem though. – fabian Nov 30 '22 at 20:00
  • 3
    If it does not return a const, you can do stupid things like `(a + b) = c` – ChrisMM Nov 30 '22 at 20:02
  • I'm not 100% sure why they need to be `const` but I have a feeling that it's got to do with the shared ownership of the data somehow. _"Behind the scenes, `QString` uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters."_ – Ted Lyngmo Nov 30 '22 at 20:06
  • @TedLyngmo I can't see how that would have anything to do with it. If the operator didn't return `const`, `(a+b) = c` would work just fine. `(a+b)` is a new object with a new value, there is no implicit sharing here. The copy would be wasted of course, but it would work. I'm fairly certain the rationale was preventing things like `(a+b) = c` as ChrisMM points out, because that would potentially reduce bugs and it was designed before move semantics were a thing. – Nelfeal Nov 30 '22 at 20:15
  • @ChrisMM is there any official statement for this being the reason though? I mean you could work around this by defining the assignment operator as deleted for rvalues: https://godbolt.org/z/TheWh9z7x – fabian Nov 30 '22 at 20:16
  • 1
    @Nelfeal The reason why I have a feeling that it's has got to do with the shared ownership is that that's the major difference I know between `std::string` and `QString`. The first non-`const` operation made on a `QString` may perform a deep copy and perhaps returning them `const` helps prevent this somehow. – Ted Lyngmo Nov 30 '22 at 20:18
  • 1
    @fabian The operator was written [before 2011-04-27](https://code.qt.io/cgit/qt/qtbase.git/commit/src/corelib/tools/qstring.h?id=38be0d13830efd2d98281c645c3a60afe05ffece), I doubt you will find any "official statement" about the reasoning behind that `const`. – Nelfeal Nov 30 '22 at 20:26
  • @fabian, no, it's just something I recall from a textbook which goes over operator overloads, and that particular textbook emphasizes returning `const` to prevent those accidental mistakes. I don't know if that was the reasoning the `Qt` did it or not though. – ChrisMM Nov 30 '22 at 20:33

0 Answers0