3

I'm building a library that generates a couple of types of objects that can be used by user code and the library. To keep track of these objects, I'd like to use shared_ptr's, so I can build in some run-time clean up. Since these are consumed by user code, I was curious if it would be worth typedefing the shared_ptr type to simplify the user code. So instead of std::shared_ptr<Foo>, user code could use FooPtr or something.

Would that be a reasonable thing to do, or is the risk of unclear code too much?

2 Answers 2

4

One of the benefits of the C++ smart pointers is that their names document ownership semantic information and memory management information.

For example:
A std::shared_ptr<Foo> clearly suggests that this instance of Foo is intended for shared usage.

Similarly, std::unique_ptr<Foo> clearly suggests that this instance is uniquely owned and exists only for the lifetime of the unique_ptr.

By hiding which pointer type you are using behind a typedef such as FooPtr you are hiding that information from your users.

Ultimately, I would say in this case hiding the information is not desirable because now your users cannot be sure who is responsible for destroying the FooPtr without referring to a comment or other documentation that you provide about FooPtr usage.

Instead, leaving it as std::shared_ptr<Foo> or std::unique_ptr<Foo> makes it clear that memory management for the Foo is handled by the ptr object itself.

0
2

With C++ it's best if there is explicit documentation about who owns what pointer and is responsible for cleanup. shared_ptr tend to muddle that and it's possible that a shared_ptr ownership-loop emerges across the user and API which can lead to leaks.

Let the user hold a small section of objects by unique_ptr and let other objects be owned (and cleaned up) by them and referenced by the user with raw pointers or references.

1
  • 1
    While the advice on shared vs unique is insightful and actually something I hadn't thought about, maybe you could also address the typedef subject? (It applies even to unique_ptr) Commented Jul 10, 2015 at 13:34

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.