[Development] Setters: Passing by value or const reference?
Thiago Macieira
thiago.macieira at intel.com
Wed Apr 25 13:44:31 CEST 2012
On quarta-feira, 25 de abril de 2012 13.57.31, Alberto Mardegan wrote:
> I understand why there wouldn't be a copy in the implementation of
> setText, but why wouldn't calling foo->setText() produce a copy?
> How can the compiler know that it must not create a copy when calling
> Foo::setText(QString text) unless we are inlining it?
Ah, you're missing the trick!
Olivier has just updated https://codereview.qt-project.org/24144 "Implement
the move consrtuctor for containers" and most other tool classes already have
move constructors.
If you have:
void setter(QString s);
and you call it with:
QString foo("foo");
setter(foo); // 1
setter(QString("bar")); //2
In both cases, the compiler must call a QString constructor because you're
passing by value. In the first case, since foo is an lvalue, it chooses
QString::QString(const QString &)
which does the normal, cheap reference counting up.
In the second case, since it's an rvalue, it chooses
QString::QString(QString &&)
which is the move constructor: it doesn't reference count up, it simply
"steals" the d pointer from the parameter and resets the parameter to
QString()
Sprinkle a few Q_ASSUME() in some places and the compiler will know that the
QString destructor for the temporary is empty.
--
Thiago Macieira - thiago.macieira (AT) intel.com
Software Architect - Intel Open Source Technology Center
Intel Sweden AB - Registration Number: 556189-6027
Knarrarnäsgatan 15, 164 40 Kista, Stockholm, Sweden
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.qt-project.org/pipermail/development/attachments/20120425/f2a490b3/attachment.sig>
More information about the Development
mailing list