“std::endl” vs “\n”

后端 未结 12 2446
耶瑟儿~
耶瑟儿~ 2020-11-21 04:35

Many C++ books contain example code like this...

std::cout << \"Test line\" << std::endl;

...so I\'ve always done that too. But

12条回答
  •  春和景丽
    2020-11-21 05:15

    If you use Qt and endl, you could accidentally end up using an incorrect endl which gives you very surprising results. See the following code snippet:

    #include 
    #include  
    #include 
    
    // notice that there is no "using namespace std;"
    int main(int argc, char** argv)
    {
        QApplication qapp(argc,argv);
        QMainWindow mw;
        mw.show();
        std::cout << "Finished Execution!" << endl;
        // This prints something similar to: "Finished Execution!67006AB4"
        return qapp.exec();
    }
    

    Note that I wrote endl instead of std::endl (which would have been correct) and apparently there is a endl function defined in qtextstream.h (which is part of QtCore).

    Using "\n" instead of endl completely sidesteps any potential namespace issues. This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.

提交回复
热议问题