Search code examples
c++qtqprocessredundancyqt5.4

Isn't the line QProcess *p redundant?


I've stumbled across this GitHub Project.

While I don't agree with the code in general I can't wrap my mind about the line:

QProcess *p; and p=*it;

Am I wrong when I feel like creating a new pointer there is completely redundant or is there some purpose of it I'm missing for example performance wise?

#define VM_COUNT 202
    cout << "Creating process objects" << endl;
    for(int i=0;i<VM_COUNT; i++)
        vms.push_back(new QProcess(parent));

    cout << "Processes created. Type 'asdf' or someting to start them...";
    string s;
    cin >> s;

    cout << "Starting processes" << endl;

    QProcess* p; // this <------
    QVector<QProcess*>::Iterator it;
    for(it=vms.begin(); it!=vms.end(); ++it){
        p=*it; // this <------
        p->start(command,args); // this <------
    }

I would simply go with:

     for(it=vms.begin(); it!=vms.end(); ++it)
     {
        (*it)->start(command,args); // ty Mike
     }

Solution

  • It is useful for code portability, or when matching an example. Say you find an example that uses QProcess * p for 100 lines, and then you apply it to a vector of processes, readability suffers when you swap out p for (*iter) in each location... but if you assign a variable with the same name at the top of the local scope, you gain readability/maintainability.

    Also Qt supports many types of iterators, STL style, Java style and a boost foreach style. I prefer the foreach style that lends it self to the the least amount of code and the highest readability for me. And it seems to be what the documentation and examples that Qt has tends to prefer, too.

    Be sure to read about mutable v immutable, when you are looking at which iterators to use.

    QList<QProcess *> listOfProcesses;
    
    // ...
    
    foreach(Process * p, listOfProcesses)
    {
        p->start();
    }
    

    And on a side note, I might write it once with p, but before I commit or leave the code, I'd do Ctrl+Shift+R in Qt Creator and rename p to process.

    Hope that helps.