By Matt Kline


2012-11-15 18:04:46 8 Comments

What is the best method to go about passing a shared_ptr of a derived type to a function that takes a shared_ptr of a base type?

I generally pass shared_ptrs by reference to avoid a needless copy:

int foo(const shared_ptr<bar>& ptr);

but this doesn't work if I try to do something like

int foo(const shared_ptr<Base>& ptr);

...

shared_ptr<Derived> bar = make_shared<Derived>();
foo(bar);

I could use

foo(dynamic_pointer_cast<Base, Derived>(bar));

but this seems sub-optimal for two reasons:

  • A dynamic_cast seems a bit excessive for a simple derived-to-base cast.
  • As I understand it, dynamic_pointer_cast creates a copy (albeit a temporary one) of the pointer to pass to the function.

Is there a better solution?

Update for posterity:

It turned out to be an issue of a missing header file. Also, what I was trying to do here is considered an antipattern. Generally,

  • Functions that don't impact an object's lifetime (i.e. the object remains valid for the duration of the function) should take a plain reference or pointer, e.g. int foo(bar& b).

  • Functions that consume an object (i.e. are the final users of a given object) should take a unique_ptr by value, e.g. int foo(unique_ptr<bar> b). Callers should std::move the value into the function.

  • Functions that extend the lifetime of an object should take a shared_ptr by value, e.g. int foo(shared_ptr<bar> b). The usual advice to avoid circular references applies.

See Herb Sutter's Back to Basics talk for details.

4 comments

@dshepherd 2018-07-24 14:08:17

This will also happen if you've forgotten to specify public inheritance on the derived class, i.e. if like me you write this:

class Derived : Base
{
};

@Phil Rosenberg 2017-10-19 18:25:16

Also check that the #include of the header file containing the full declaration of the derived class is in your source file.

I had this problem. The std::shared<derived> would not cast to std::shared<base>. I had forward declared both classes so that I could hold pointers to them, but because I didn't have the #include the compiler could not see that one class was derived from the other.

@nobism 2019-01-24 02:49:53

Wow, I didn't expect it but this fixed it for me. I was being extra careful and only including header files where I needed them so some of them were only in source files and forward declaring them in headers as you said.

@Bret Kuhns 2012-11-15 18:14:31

Although Base and Derived are covariant and raw pointers to them will act accordingly, shared_ptr<Base> and shared_ptr<Derived> are not covariant. The dynamic_pointer_cast is the correct and simplest way to handle this problem.

(Edit: static_pointer_cast would be more appropriate because you're casting from derived to base, which is safe and doesn't require runtime checks. See comments below.)

However, if your foo() function doesn't wish to take part in extending the lifetime (or, rather, take part in the shared ownership of the object), then its best to accept a const Base& and dereference the shared_ptr when passing it to foo().

void foo(const Base& base);
[...]
shared_ptr<Derived> spDerived = getDerived();
foo(*spDerived);

As an aside, because shared_ptr types cannot be covariant, the rules of implicit conversions across covariant return types does not apply when returning types of shared_ptr<T>.

@Mike Seymour 2012-11-15 18:16:31

They're not covariant, but shared_ptr<Derived> is implicitly convertible to shared_ptr<Base>, so the code should work with no casting shenanigans.

@Pete Becker 2012-11-15 18:17:56

Um, shared_ptr<Ty> has a constructor that takes a shared_ptr<Other> and does the appropriate conversion if Ty* is implicitly convertible to Other*. And if a cast is needed, static_pointer_cast is the appropriate one here, not dynamic_pointer_cast.

@Bret Kuhns 2012-11-15 18:20:29

True, but not with his reference parameter, as in the question. He would need to do a copy, regardless. But, if he's using refs to shared_ptr's to avoid the reference count, then there's really no good reason to be using a shared_ptr in the first place. It's best to use const Base& instead.

@Bret Kuhns 2012-11-15 18:21:24

@PeteBecker See my comment to Mike about the conversion constructor. I honestly didn't know about static_pointer_cast, thanks.

@Damian 2017-12-12 05:51:40

I will use dynamic_pointer_cast great reference!

@Kim Homann 2019-03-14 14:30:47

In cplusplus.com/reference/memory/static_pointer_cast it says: "If sp is not empty, the returned object shares ownership over sp's resources, increasing by one the use count." Isn't it possible to pass by reference without increasing the ref count?

@Bret Kuhns 2019-04-03 20:13:46

@KimHomann the reference count would not increase in the example from my answer. Passing the pointed-to object by reference (eg, const Foobar&) does not cause std::shared_ptr to affect the count. Using static_pointer_cast (or dynamic_point_cast), however, will affect the reference count. The latter has to because it is participating in the lifetime of the object.

@Pete Becker 2012-11-15 18:30:21

Sounds like you're trying too hard. shared_ptr is cheap to copy; that's one of its goals. Passing them around by reference doesn't really accomplish much. If you don't want sharing, pass the raw pointer.

That said, there are two ways to do this that I can think of off the top of my head:

foo(shared_ptr<Base>(bar));
foo(static_pointer_cast<Base>(bar));

@Seth Carnegie 2012-11-15 18:31:03

No, they're not cheap to copy, they should be passed by reference whenever possible.

@Pete Becker 2012-11-15 18:32:41

@SethCarnegie - do you have measurements to establish that its a bottleneck in your code? It's just an atomic integer increment.

@Seth Carnegie 2012-11-15 18:33:21

I'm just saying what Herb Sutter says. Watch channel9.msdn.com/Shows/Going+Deep/… and go to 4:34

@Pete Becker 2012-11-15 18:35:01

@SethCarnegie - did Herb profile your code to see whether passing by value was a bottleneck?

@Seth Carnegie 2012-11-15 18:36:01

I trust Sutter more than you. You didn't profile my code either to determine it's not a bottleneck, so it's you vs. him, and he wins.

@Pete Becker 2012-11-15 18:37:42

@SethCarnegie - that doesn't answer the question I asked. And, for what it's worth, I wrote the shared_ptr implementation that Microsoft ships.

@Matt Kline 2012-11-15 18:37:50

@PeteBecker: It has a definite cost, and should be avoided when possible. See this thread

@Pete Becker 2012-11-15 18:39:53

@slavik262 - no, it sometimes should be avoided. Like any hand optimization, it should be done if you have evidence that it's a bottleneck in your program. If I pass half a dozen shared_ptr objects in two dozen places, there's no reason at all to complicate things by passing them by reference.

@Pete Becker 2012-11-15 18:41:03

@SethCarnegie - you've got the heuristic backwards. Hand optimizations should generally not be done unless you can show that they are needed.

@Seth Carnegie 2012-11-15 18:44:14

@PeteBecker (regarding you writing the MSVC implementation of shared_ptr) then I find it amazing that you don't concede to Herb Sutter knowing what you know. I did answer your question, just not with the answer you wanted. When it's something as trivial as passing by reference, it doesn't complicate things. Not passing by reference is premature pessimisation. Why pass stuff by value for the heck of it? Seriously, if someone like Sutter recommends something, you don't really change your mind unless someone else you respect more recommends the opposite, and that's not happening here.

@Mark Ransom 2012-11-15 18:46:03

It's only "premature" optimization if you need to work at it. I see no problem in adopting efficient idioms over inefficient ones, whether it makes a difference in a particular context or not.

@Pete Becker 2012-11-15 18:46:38

@SethCarnegie - if "it doesn't complicate things", why did the original poster have to ask how to do it?

@Jean-Michaël Celerier 2016-08-04 09:45:04

@PeteBecker "Hand optimizations should generally not be done unless you can show that they are needed." writing const Foo& instead of std::shared_ptr<Foo> is certainly an optimization for my both hands. Seriously, if it takes less time to write, is more clear, AND is faster, it isn't an optimization, it is mandatory.

@Chris O 2016-10-20 18:35:05

@MarkRansom In this case, you do need to work at it, you have to prove that foo won't call anything that will implicitly cause ptr to be deleted, thus leading to AV, if the rest of foo attempts to use the smart-pointer-as-reference. (This was actually a problem in one codebase I've maintained, though to be fair, things might not have been "as tight" as they should have been).

@Tom Mettam 2019-03-04 14:55:20

The performance degradation doesn't come at assignment time, but when the refcount is decremented. Please see this answer (not the accepted one) for a concise description: stackoverflow.com/questions/16966043/…

Related Questions

Sponsored Content

35 Answered Questions

1 Answered Questions

16 Answered Questions

[SOLVED] When to use references vs. pointers

3 Answered Questions

[SOLVED] Downcasting shared_ptr<Base> to shared_ptr<Derived>?

  • 2009-08-31 16:02:56
  • Lajos Nagy
  • 58392 View
  • 82 Score
  • 3 Answer
  • Tags:   c++ gcc boost

1 Answered Questions

2 Answered Questions

[SOLVED] How to pass shared_ptr to class with lower lifetime?

1 Answered Questions

[SOLVED] Base class unique_ptr to derived class shared_ptr

4 Answered Questions

[SOLVED] How to pass a shared_ptr to a mutable object as a parameter?

8 Answered Questions

[SOLVED] When to pass by reference and when to pass by pointer in C++?

  • 2010-08-31 20:42:15
  • user855
  • 20849 View
  • 44 Score
  • 8 Answer
  • Tags:   c++

Sponsored Content