Why doesn't C++ reimplement C standard functions with C++ elements/style?

后端 未结 10 2582
花落未央
花落未央 2020-12-10 05:46

For a specific example, consider atoi(const std::string &). This is very frustrating, since we as programmers would need to use it so much.

10条回答
  •  失恋的感觉
    2020-12-10 05:52

    I see that solutions are offered that use std::stringstream or std::istringstream. This might be perfectly OK for single threaded applications but if an application has lots of threads and often calls atoi(const std::string& str) implemented in this way that will result in performance degradation.

    Read this discussion for example: http://gcc.gnu.org/ml/gcc-bugs/2009-05/msg00798.html. And see a backtrace of the constructor of std::istringstream:

    #0  0x200000007eb77810:0 in pthread_mutex_unlock+0x10 ()
       from /usr/lib/hpux32/libc.so.1
    #1  0x200000007ef22590 in std::locale::locale (this=0x7fffeee8)
        at gthr-default.h:704
    #2  0x200000007ef29500 in std::ios_base::ios_base (this=)
        at /tmp/gcc-4.3.1.tar.gz/gcc-4.3.1/libstdc++-v3/src/ios.cc:83
    #3  0x200000007ee8cd70 in std::basic_istringstream,std::allocator >::basic_istringstream (this=0x7fffee4c,
        __str=@0x7fffee44, __mode=_S_in) at basic_ios.h:456
    #4  0x4000f70:0 in main () at main.cpp:7
    

    So every time you enter atoi() and create a local varibale of type std::stringstream you will lock a global mutex and in a multithreaded application it is likely to result in waiting on this mutex.

    So, it's better in a multithreaded application not to use std::stringstream. For example simply call atoi(const char*):

    inline int atoi(const std::string& str)
    {
        return atoi(str.c_str());
    }
    

提交回复
热议问题