User:Fresbeeplayer/Translate ErroriProgrammazioneComuni: Difference between revisions

    From KDE TechBase
    mNo edit summary
    mNo edit summary
    Line 286: Line 286:
    === Iteratori ===
    === Iteratori ===


    <!-- ==== Prefer const iterators and cache end() ====
    <!-- ==== Prefer const iterators and cache end() ==== -->
    Prefer to use <tt>const_iterators</tt> over normal iterators when possible. Containers, which are being implicitly shared often detach when a call to a non-const <tt>begin()</tt> or <tt>end()</tt> methods is made ({{qt|QList}} is an example of such a container). When using a const_iterator also watch out that you are really calling the const version of <tt>begin()</tt> and <tt>end()</tt>. Unless your container is actually const itself this probably will not be the case, possibly causing an unnecessary detach of your container. So basically whenever you use const_iterator initialize them using <tt>constBegin()</tt>/<tt>constEnd()</tt> instead, to be on the safe side. -->
    <! --Prefer to use <tt>const_iterators</tt> over normal iterators when possible. Containers, which are being implicitly shared often detach when a call to a non-const <tt>begin()</tt> or <tt>end()</tt> methods is made ({{qt|QList}} is an example of such a container). When using a const_iterator also watch out that you are really calling the const version of <tt>begin()</tt> and <tt>end()</tt>. Unless your container is actually const itself this probably will not be the case, possibly causing an unnecessary detach of your container. So basically whenever you use const_iterator initialize them using <tt>constBegin()</tt>/<tt>constEnd()</tt> instead, to be on the safe side. -->


    ==== Preferire iteratori costanti e conservare end() ====
    ==== Preferire iteratori costanti e conservare end() ====

    Revision as of 11:32, 27 November 2008


    Development/Tutorials/Common Programming Mistakes


    Errori di Programmazione Comuni
    Tutorial Series   Getting Started
    Previous   None
    What's Next   n/a
    Further Reading   APIs to avoid

    Prefazione

    Questo tutorial mira a combinare le esperienze degli sviluppatori KDE su cosa fare e cosa non fare in merito alle librerie Qt e KDE. Oltre agli errori, vengono coperte anche cose che non sono necessariamente "bachi" ma che rendono il codice più lento e di difficile lettura.

    C++ in generale

    Questa sezione ti guida attraverso alcuni degli angoli più remoti del C++ che tendono ad essere usati male o dei quali la gente si sbaglia.

    Namespace anonimi contro static

    Se hai un metodo in una classe che non accede ad alcun membro e quindi non ha bisogno di un oggetto per funzionare, rendilo statico. Se in più è una funzione di supporto privata che non viene utilizzata all'esterno del file, rendila file-static. In questo modo essa viene nascosta completamente.


    Le entità definite in un namespace anonimo in C++ non hanno linkage interni. I namespace anonimi offrono soltanto un nome unico per quella translation unit e basta; non cambiano in nessun modo il linkage dell'identificatore. Il linkage non viene cambiato perché la seconda delle due fasi di ricerca dei nomi ignora le funzioni con linkage interno. Per di più, le entità con linkage interno non possono essere usate come argomento di un template.


    A questo punto invece di usare namespace anonimi usa la parola chiave static se non vuoi che un simbolo venga esportato.

    Problemi di puntatore Nullo

    Prima di tutto: va bene eliminare un puntatore nullo. Quindi costruttori come il seguente che controllano che il valore sia nullo prima di eliminarlo sono semplicemente ridondanti:

    if ( ptr ) {

      delete ptr;
    

    }


    Da notare comunque, che un controllo per valore nullo è richiesto quando cancelli un array - questo perché altrimenti un compilatore relativamente recente per Solaris non lo gestisce opportunamente.


    Quando elimini un puntatore, assicurati anche di settarlo a 0 in modo che futuri tentativi di cancellazione non falliscano in una doppia eliminazione. Per cui il modo completo e corretto di procedere è:

    delete ptr; ptr = 0;


    Potresti notare che i puntatori nulli sono variamente indicati in uno di questi tre modi: 0, 0L e NULL. In C, NULL è definito come un puntatore nullo di tipo void. Ma in C++ ciò non è possibile a causa di un controllo di tipo più stretto. Perciò, moderne implementazioni del C++ lo rendono come un "magico" puntatore nullo costante il quale può essere assegnato a qualunque altro puntatore. D'altra parte le implementazioni più vecchie di C++ semplicemente lo associano a 0 o 0L, il quale non tiene conto di alcuna sicurezza di tipo - si potrebbe assegnarlo ad una variabile intera, ovviamente sbagliando.


    Nel contesto dei puntatori, la costante intera zero significa "puntatore nullo" - irrispettoso della rappresentazione binaria di un puntatore nullo. Ciò significa che la scelta tra 0, 0L e NULL è una questione di stile personale e abitudine piuttosto che tecnica - fintantoché nel codice SVN di KDE vedrai 0 usato più comunemente di NULL.


    Notare, comunque, che se vuoi passare un puntatore nullo costante ad una funzione nella lista delle variabili degli argomenti, *devi* esplicitamente farne il cast in un puntatore - il compilatore assume di default il contesto degli interi, il quale può o non può coincidere con la rappresentazione binaria di un puntatore. Di nuovo, non ha importanza il fatto che fai il cast a 0, 0L o NULL, ma la rappresentazione più corta è generalmente preferita.

    Variabili membro

    Incontrerai quattro maggiori stili per segnare le variabili membre delle classi in KDE:

    • m_variabile m minuscola, underscore ed il nome della variabile che comincia con una lettera minuscola. Questo è lo stile più comune ed uno dei preferiti nel codice delle kdelibs.
    • mVariabile m minuscola ed il nome della variabile che comincia con una lettera maiuscola.
    • variabile_ il nome della variabile comincia con la lettera minuscola ed alla fine un underscore.
    • _variabile un underscore e poi il nome della variabile con la lettera iniziale minuscola. Questa notazione di solito è sconsigliata siccome è anche utilizzata in qualche codice per i parametri delle funzioni.


    Come accade spesso non c'è un modo corretto per farlo, perciò ricorda sempre di rispettare la sintassi utilizzata dall'applicazione/libreria alla quale stai facendo commit.

    Variabili statiche

    Cerca di limitare il numero di variabili statiche nel tuo codice, specialmente quando fate il commit per una libreria. Costruzione ed inizializzazione di un grande numero di variabili statiche fa veramente male ai tempi di avvio.


    Non usare variabili class-static, in particolare non nelle librerie e nei moduli sebbene sia anche scoraggiato nelle applicazioni. Oggetti statici portano ad un sacco di problemi tra cui difficoltà di debug dei crash dovuto ad un ordine indefinito di costruttore/distruttore.


    Invece, usa un puntatore statico insieme a K_GLOBAL_STATIC definito in kglobal.h ed usato in questo modo:


    class A { ... };

    K_GLOBAL_STATIC(A, globaleA)

    void faQualcosa() {

        A *a = globaleA;
        ...
    

    }

    void faQualcosAltro() {

       if (globaleA.isDestroyed()) {
           return;
       }
       A *a = globaleA;
       ...
    

    }

    void installaPostRoutine() {

       qAddPostRoutine(globaleA.destroy);
    

    }


    Vedi la documentazione delle API per più informazioni su K_GLOBAL_STATIC.

    Dati costanti

    Se hai bisogno di qualche dato costante per semplici tipi di dato in molti punti, fai bene a definirli una volta sola in un posto centrale, onde evitare errori di digitazione in una delle istanze. Se i dati cambiano hai bisogno di editare solo in un punto.


    Anche se usati una sola volta è meglio definirli da un'altra parte, per evitare inspiegabili "numeri magici" nel codice (cmp. 42). Di solito ciò viene fatto in cima al file per non doverli ricercare.


    Definisci i dati costanti usando i costrutti del C++, non le istruzioni del preprocessore, come potresti essere abituato a fare dal C. In questo modo il compilatore può aiutarti a trovare errori facendo il controllo di tipo.


    // Corretto! static const int LaRispostaATutteLeDomande = 42; // Sbagliato!

    1. define LaRispostaATutteLeDomande 42


    Se stai definendo un array costante non usare un puntatore come tipo di dato. Invece usa il suo tipo ed appendi il simbolo dell'array di indefinita lunghezza, [], dopo il nome. Altrimenti definirai anche una variabile che punta a qualche dato costante. La variabile potrebbe per sbaglio essere assegnata ad un altro puntatore, senza che il compilatore se ne lamenti. E l'accesso all'array sarebbe indiretto, perché per primo deve essere letto il valore della variabile.


    // Corretto! static const char UnaStringa[] = "Esempio"; // Sbagliato! static const char* UnaStringa = "Esempio"; // Sbagliato!

    1. define UnaStringa "Esempio"

    Dichiarazioni anticipate

    Ridurrai i tempi di compilazione dichiarando anticipatamente le classi quando possibile invece di includere i rispettivi headers. Per esempio:


    1. include <QWidget> // lento
    2. include <QStringList> // lento
    3. include <QString> // lento

    class QualcheInterfaccia { public:

       virtual void azioneWidget( QWidget *widget ) =0;
       virtual void azioneStringa( const QString& str ) =0;
       virtual void azioniListaStringhe( const QStringList& strLista ) =0;
    

    };

    Dovrebbe invece essere scritto in questo modo:


    class QWidget; // veloce class QStringList; // veloce class QString; // veloce class QualcheInterfaccia { public:

       virtual void azioneWidget( QWidget *widget ) =0;
       virtual void azioneStringa( const QString& str ) =0;
       virtual void azioniListaStringhe( const QStringList& strLista ) =0;
    

    };

    Iteratori

    <! --Prefer to use const_iterators over normal iterators when possible. Containers, which are being implicitly shared often detach when a call to a non-const begin() or end() methods is made (QList is an example of such a container). When using a const_iterator also watch out that you are really calling the const version of begin() and end(). Unless your container is actually const itself this probably will not be the case, possibly causing an unnecessary detach of your container. So basically whenever you use const_iterator initialize them using constBegin()/constEnd() instead, to be on the safe side. -->

    Preferire iteratori costanti e conservare end()

    Preferire l'uso dei const_iterators rispetto ai normali iteratori quando possibile. I containers, implicitamente condivisi, spesso

    Cache the return of the end() (or constEnd()) method call before doing iteration over large containers. For example:

    QValueList<SomeClass> container;

    //code which inserts a large number of elements to the container

    QValueListConstIterator end( container.constEnd() );

    for ( QValueListConstIterator itr( container.constBegin() );

        itr != end; ++itr ) {
    

    }

    This avoids the unnecessary creation of the temporary end() (or constEnd()) return object on each loop iteration, largely speeding it up.

    Prefer to use pre-increment over post-increment operators on iterators as this avoids creating an unnecessary temporary object in the process.

    Take care when erasing elements inside a loop

    When you want to erase some elements from the list, you maybe would use code similar to this:

    QMap<int, Job *>::iterator it = m_activeTimers.begin(); QMap<int, Job *>::iterator itEnd = m_activeTimers.end();

    for( ; it!=itEnd ; ++it ) {

       if(it.value() == job)
       {
           //A timer for this job has been found. Let's stop it.
           killTimer(it.key());
           m_activeTimers.erase(it);
       }
    

    }

    This code will potentially crash because it is a dangling iterator after the call to erase(). You have to rewrite the code this way: QMap<int, Job *>::iterator it = m_activeTimers.begin(); while (it != m_activeTimers.end()) {

       QMap<int, Job *>::iterator prev = it;
       ++it;
       if(prev.value() == job)
       {
           //A timer for this job has been found. Let's stop it.
           killTimer(prev.key());
           m_activeTimers.erase(prev);
       }
    

    } This problem is also discussed in the Qt documentation for QMap::iterator but applies to all Qt iterators

    memory leaks

    A very "popular" programming mistake is to do a new without a delete like in this program:

    mem_gourmet.cpp class t {

     public:
       t() {}
    

    };

    void pollute() {

     t* polluter = new t();
    

    }

    int main() {

     while (true) pollute();
    

    }

    You see, pollute() instanciates a new object polluter of the class t. Then, the variable polluter is lost because it is local, but the content (the object) stays on the heap. I could use this program to render my computer unusable within 10 seconds.

    To solve this, there are the following approaches:

    • keep the variable on the stack instead of the heap:

     t* polluter = new t();
    

    would become

     t polluter();
    

    • delete polluter using the complementing function to new:

     delete polluter;
    

    A tool to detect memory leaks like this is Valgrind.

    dynamic_cast

    You can only dynamic_cast to type T from type T2 provided that:

    • T is defined in a library you link to (you'd get a linker error if this isn't the case, since it won't find

    the vtable or RTTI info)

    • T is "well-anchored" in that library. By "well-anchored" I mean that the vtable is not a COMMON symbol subject to merging at run-time by the dynamic linker. In other words, the first virtual member in the class definition must exist and not be inlined: it must be in a .cpp file.
    • T and T2 are exported

    For instance, we've seen some hard-to-track problems in non-KDE C++ code we're linking with (I think NMM) because of that. It happened that:

    • libphonon loads the NMM plugin
    • NMM plugin links to NMM
    • NMM loads its own plugins
    • NMM's own plugins link to NMM

    Some classes in the NMM library did not have well-anchored vtables, so dynamic_casting failed inside the Phonon NMM plugin for objects created in the NMM's own plugins.

    Program Design

    In this section we will go over some common problems related to the design of Qt/KDE applications.

    Delayed Initialization

    Although the design of modern C++ applications can be very complex, one recurring problem, which is generally easy to fix, is not using the technique of delayed initialization.

    First, let us look at the standard way of initializing a KDE application:

    int main( int argc, char **argv ) {

       ....
       KApplication a;
    
       KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    
       MainWindow *window = new MainWindow( args );
    
       a.setMainWidget( window );
       window->show();
    
       return a.exec();
    

    }

    Notice that window is created before the a.exec() call that starts the event loop. This implies that we want to avoid doing anything non-trivial in the top-level constructor, since it runs before we can even show the window.

    The solution is simple: we need to delay the construction of anything besides the GUI until after the event loop has started. Here is how the example class MainWindow's constructor could look to achieve this:

    MainWindow::MainWindow() {

       initGUI();
       QTimer::singleShot( 0, this, SLOT(initObject()) );
    

    }

    void MainWindow::initGUI() {

       /* Construct your widgets here.  Note that the widgets you
        * construct here shouldn't require complex initialization
        * either, or you've defeated the purpose.
        * All you want to do is create your GUI objects and
        * QObject::connect
        * the appropriate signals to their slots.
        */
    

    }

    void MainWindow::initObject() {

       /* This slot will be called as soon as the event loop starts.
        * Put everything else that needs to be done, including
        * restoring values, reading files, session restoring, etc here.
        * It will still take time, but at least your window will be
        * on the screen, making your app look active.
        */
    

    }

    Using this technique may not buy you any overall time, but it makes your app seem quicker to the user who is starting it. This increased perceived responsiveness is reassuring for the user as they get quick feedback that the action of launching the app has succeeded.

    When (and only when) the start up can not be made reasonably fast enough, consider using a KSplashScreen.

    Data Structures

    In this section we will go over some of our most common pet-peeves which affect data structures very commonly seen in Qt/KDE applications.

    Passing non-POD types

    Non-POD ("plain old data") types should be passed by const reference if at all possible. This includes anything other than the basic types such as char and int.

    Take, for instance, QString. They should always be passed into methods as const QString&. Even though QString is implicitly shared it is still more efficient (and safer) to pass const references as opposed to objects by value.

    So the canonical signature of a method taking QString arguments is:

    void myMethod( const QString & foo, const QString & bar );

    QObject

    If you ever need to delete a QObject derived class from within one of its own methods, do not ever delete it this way:

      delete this;
    

    This will sooner or later cause a crash because a method on that object might be invoked from the Qt event loop via slots/signals after you deleted it.

    Instead always use QObject::deleteLater() which tries to do the same thing as delete this but in a safer way.

    Empty QStrings

    It is common to want to see if a QString is empty. Here are three ways of doing it, the first two of which are correct:

    // Correct if ( mystring.isEmpty() ) { }

    // Correct if ( mystring == QString() ) { }

    // Wrong! "" if ( mystring == "" ) { }

    While there is a distinction between "null" QStrings and empty ones, this is a purely historical artifact and new code is discouraged from making use of it.

    QString and reading files

    If you are reading in a file, it is faster to convert it from the local encoding to Unicode (QString) in one go, rather than line by line. This means that methods like QIODevice::readAll() are often a good solution, followed by a single QString instantiation.

    For larger files, consider reading a block of lines and then performing the conversion. That way you get the opportunity to update your GUI. This can be accomplished by reentering the event loop normally, along with using a timer to read in the blocks in the background, or by creating a local event loop.

    While one can also use qApp->processEvents(), it is discouraged as it easily leads to subtle yet often fatal problems.

    Reading QString from a KProcess

    KProcess emits the signals readyReadStandard{Output|Error} as data comes in. A common mistake is reading all available data in the connected slot and converting it to QString right away: the data comes in arbitrarily segmented chunks, so multi-byte characters might be cut into pieces and thus invalidated. Several approaches to this problem exist:

    • Do you really need to process the data as it comes in? If not, just use readAllStandard{Output|Error} after the process has exited. Unlike in KDE3, KProcess is now able to accumulate the data for you.
    • Wrap the process into a QTextStream and read line-wise. This should work starting with Qt 4.4.
    • Accumulate data chunks in the slots and process them each time a newline arrives or after some timeout passes. Example code

    QString and QByteArray

    While QString is the tool of choice for many string handling situations, there is one where it is particularly inefficient. If you are pushing about and working on data in QByteArrays, take care not to pass it through methods which take QString parameters; then make QByteArrays from them again.

    For example:

    QByteArray myData; QString myNewData = mangleData( myData );

    QString mangleData( const QString& data ) {

       QByteArray str = data.toLatin1();
       // mangle 
       return QString(str);
    

    }

    The expensive thing happening here is the conversion to QString, which does a conversion to Unicode internally. This is unnecessary because, the first thing the method does is convert it back using toLatin1(). So if you are sure that the Unicode conversion is not needed, try to avoid inadvertently using QString along the way.

    The above example should instead be written as:

    QByteArray myData; QByteArray myNewData = mangleData( myData );

    QByteArray mangleData( const QByteArray& data )

    QDomElement

    When parsing XML documents, one often needs to iterate over all the elements. You may be tempted to use the following code for that:

    for ( QDomElement e = baseElement.firstChild().toElement();

         !e.isNull();
         e = e.nextSibling().toElement() ) {
          ...
    

    }

    That is not correct though: the above loop will stop prematurely when it encounters a QDomNode that is something other than an element such as a comment.

    The correct loop looks like:

    for ( QDomNode n = baseElement.firstChild(); !n.isNull();

         n = n.nextSibling() ) {
       QDomElement e = n.toElement();
       if ( e.isNull() ) {
           continue;
       }
       ...
    

    }