Search code examples
c++shared-ptrreturn-value-optimization

Does a temporary shared_ptr returned by value have the counter incremented?


I'm trying to understand how RVO works in conjunction with shared_ptr in this particular case.

Let's say I have this example code:

class A {
public:
  void action() {}
};

class Container {
public:
  shared_ptr<A> getA() { return m_a; }

private:
  shared_ptr<A> m_a;
};

Container cont{};
cont.getA()->action();

If I'm not wrong, in this situation the shared_ptr returned by getA() shouldn’t be copied/copy constructed because it's optimized by the compiler. So, in the last line, the shared_ptr I'm calling the action() function on should be directly the one contained in m_a inside the Container object?

In this case, if the pointer is not copied, is the internal reference count not incremented/decremented?

And because I'm using it as an r-value, it's optimized and I can directly use it to access the pointed object without any cost, like a raw pointer?

In case it's not like that, is there a way to avoid the cost of the increment/decrement? I'm not actually keeping the shared_ptr, but I'm using it only for an operation on the contained object.

Or, there could be any problem with the lifetime of the contained object?


Solution

  • the shared_ptr returned by getA() shouldn’t be copied/copy constructed because it’s optimized by the compiler.

    Yes, it will be copied. m_a is not a local variable so NRVO (named return value optimization) can't be done and returning it by value will indeed copy construct the returned shared_ptr<A>.

    Demo