Search code examples
c++pointersc++11pass-by-referencepass-by-pointer

Why should I prefer references on smart pointers over smart pointers as parameters in C++


I am currently working on some code (c++11), which makes heavy use of references on pointers, e.g.

class SomeClass;

class MyClass
{
public:
   MyClass( const std::shared_ptr < SomeClass > & class) 
    : m_class(class)
   {}

private:
   std::shared_ptr < SomeClass > m_class
}

I made some tests on the performance on this (using Visual Studio 2013 VC12) and there seems to be no difference in time. Handing over a Null-Ptr is also okay.

So what are possible reasons for using a reference in this case?


Solution

  • The possible reasons are:

    1. Performance. It should be faster to pass a reference (one CPU register) rather than a smart pointer by value. There is something wrong with your performance tests.
    2. Saving stack space. A smart-pointer passed by value takes more space on the stack than a reference.