Search code examples
shared-ptr

Local copy 'xxx' of the variable 'xxx' is never modified;


shared_ptr<int> sp1(new int(10));
shared_ptr<int> sp3(sp1);
*sp3 = 20;

I wrote the code above, but clion advises me that 'Clang-Tidy: Local copy 'sp3' of the variable 'sp1' is never modified; consider avoiding the copy';and clion modifies my code to below:

I want to konw why clion give me that advise and why const shared_ptr<int>& sp3(sp1); is the best thank you!


Solution

  • Copying any large object generally costs more than just referencing it (, and the reference can sometimes be optimized by the compiler). clang-tidy is smart enough to detect that you never modify sp3 and the copy can be avoided.

    If you only wonder why clang-tidy gives you this suggestion, you can stop here, since it will give you the same suggestion whatever class you use. The following paragraphs explain how copying a shared pointer can be expensive.

    This represents your original code:

          contains
    sp3 --------------
     | copy of        \
     |                 \       ______________
     V    contains      \     |     ...      | points to
    sp1 --------------------> | new int(10) -+----------> 10
                              |______________|
                                control block
    

    By using const shared_ptr<int>& sp3(sp1); you create a reference to sp1, and you can still change the value the raw pointer points to. The const & only means you cannot modify sp1 by sp3.

                                 ______________
           &        contains    |     ...      | points to
    sp3 ------>sp1 -----------> | new int(10) -+----------> 10
                                |______________|
                                  control block
    

    The control block is used for reference counting and ensures thread-safety by atomic operations, which costs much more time than just copying bytes. That's why you should only copy a std::shared_ptr<?> when you really need to. (e.g. Pass it to another thread or store it in a graph structure)