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

303 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.