[Qt-interest] Qt code compiles fine on mscv9.0 but failed with gcc
Constantin Makshin
cmakshin at gmail.com
Wed Jan 26 20:58:40 CET 2011
I didn't say it's a good idea to pass temporary objects as non-const reference parameters and, especially, to keep a reference without being sure it won't become invalid before you use it.
Also, your example isn't exactly what I were talking about — your example tries to modify a non-existing object (which is destroyed when "Foo" class constructor returns control to function()) while I meant the case where a function modifies an object it receives. Something like this:
class Foo
{
void bar (QString& s)
{
s += "ghi";
}
Foo (QString& s)
{
s = "def";
bar(s);
}
};
void function ()
{
Foo f(QString("abc"));
}
In this case Foo::Foo() can do everything it wants with the object it receives, but any changes will be lost because the object is destroyed after control returns to function(). And no dangling pointers or other similar problems because the temporary object isn't used anywhere outside Foo::Foo() or other function it calls.
I admit it's safer to forbid such usage to make code less error-prone, but at the same time I think it's not as bad as you say. Correct me if I'm wrong.
On Wednesday 26 January 2011 19:17:27 Thiago Macieira wrote:
> Em quarta-feira, 26 de janeiro de 2011, às 18:39:07, Constantin Makshin
> escreveu:
> > I guess that in MSVC, when you pass a temporary object as a non-const
> > reference and then the function modifies this referenced object, it
> > modifies the temporary object.
> [snip]
> > then the only difference from the first example is that any changes are lost
> > when the temporary object is destroyed, i.e. when someFunc() finishes its
> > work.
> >
> > While this behavior may be wrong from C++ point of view, it has some sense
> > IMHO.
>
> No, it's completely wrong. It violates RAII and it enables this:
>
> struct Foo
> {
> QString &s;
> Foo(QString &s) : s(s) {}
> };
>
> void function()
> {
> Foo f(QString("abc"));
> f.s = "def";
> }
>
> The Foo::s member of f was initialised as a non-const lvalue ref to a
> temporary. The temporary was subsequently destroyed at the end of that
> statement. But then we proceeded to use it on the next statement,
> dereferencing a dangling pointer (s.QString::d).
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 490 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110126/d795f5dc/attachment.bin
More information about the Qt-interest-old
mailing list