C++ Smart Pointer performance

前端 未结 6 1720
北荒
北荒 2021-02-07 05:24

How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance i

6条回答
  •  天涯浪人
    2021-02-07 06:05

    Boost provide different smart pointers. Generally both the memory occupation, which varies in accordance to the kind of smart pointer, and the performance should not be an issue. For a performance comparison you can check this http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smarttests.htm.

    As you can see only construction, copy and destruction are taken into account for the performance comparison, which means that dereferencing a smart pointer has supposedly the same cost as that of a raw pointer.

    The following snippet demonstrates that there's no performance loss by using a shared_ptr<> in place of a raw pointer:

    #include 
    #include 
    
    int main()
    {
    #ifdef USE_SHARED_PTR
        std::tr1::shared_ptr i(new int(1));
    #else
        volatile int * i = new int(1);
    #endif
    
        long long int h = 0;
    
        for(long long int j=0;j < 10000000000LL; j++)
        {
            h += *i;
        }
    
        std::cout << h << std::endl;
        return 0;
    }
    

提交回复
热议问题