[Qt-interest] A new (?) const-correct way to create a Ui object and do setupUi

Nikos Chantziaras realnc at arcor.de
Tue Feb 8 12:24:12 CET 2011


On 02/08/2011 01:00 PM, Thiago Macieira wrote:
> Em terça-feira, 8 de fevereiro de 2011, às 11:33:38, Niels Dekker escreveu:
>> However, this approach causes extra header file dependencies. So
>> doc.qt.nokia.com also presents an alternative, removing the #include
>> "ui_calculatorform.h" from the header file, and declaring the Ui member
>> variable as a pointer. I certainly find this an interesting alternative. But
>> instead of a pointer, I'd rather have a reference. Or even better: a const
>> reference!
>> Protecting the Ui object against any accidental modifications!
>
> Why a reference? What's the advantage here? In all platforms, references are
> just pre-dereferenced pointers. And how do you delete the reference
> afterwards?

I think they're more than just pre-dereferenced pointers.  They alter 
code semantics and behavior.  For example consider this:

   const QString& tmpRef = QString::fromAscii("Reference");
   std::cout << tmpRef.toLocal8Bit().constData();

And this:

   const QString* tmpPnt = &QString::fromAscii("Pointer");
   std::cout << tmpPnt->toLocal8Bit().constData();

The first example is correct and perfectly safe; taking a reference to a 
temporary effectively gives it a name and prevents it from going out of 
scope.

The second example is not correct because you're taking the address of a 
temporary which does not exist anymore when you print it to cout.

This has nothing to do with the OP though :-)  I only posted this 
because people might think that references are just pointers that don't 
need the "->" operator, which is definitely not the case.



More information about the Qt-interest-old mailing list