c++ - Use of shared pointers in public interfaces -


we have pretty standard tree api using shared pointers looks (implementations omitted brevity):

class node; using node_ptr = std::shared_ptr<node>;  class node : public std::enable_shared_from_this<node> {     std::weak_ptr<node> parent;     std::vector<node_ptr> children;  public:     virtual ~node() = default;      virtual void do_something() = 0;      void add_child(node_ptr new_child);      void remove_child(node_ptr child);      node_ptr get_parent();      const std::vector<node_ptr>& get_children(); };  class derived_node : public node {     derived_node() = default;  public:     virtual void do_something() override;      static node_ptr create(/* args... */); };  // more derived node types... 

this works fine , prevents nodes being leaked you'd imagine. however, i've read on various other answers on using std::shared_ptr in public api considered bad style , should avoided.

obviously ventures opinion-based territory, couple of concrete questions avoid question being closed :-)

  • are there well-known pitfalls using shared_ptrs in interfaces this, have far been fortunate enough avoid?

  • if so, there commonly-used (i hesitate "idiomatic") alternative formulation avoids said pitfalls still allows simple memory management users?

thanks.

its not bad style, depends on goals, , assumptions.

a few projects i've worked on hard restraints required avoid shared_ptrs because wanted manage our own memory. use of 3rd party libs require use shared_ptrs out.

another reason might wish avoid shared_ptrs opinionated. projects wrap around , pretend having gc language (urg!). other projects treat shared_ptrs little more restraint, , use shared_ptr's when comes down things have shared ownership.

most of 3rd party api (certainly not all) i've worked operate on principle if you've allocated it, destroy it. long clear ownership of resource doesn't cause issue.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -