Featured post
visual studio 2010 - Ways to make it easier to work with shared pointers in C++ -
i busy designing new c++ application. in application want minimize potential errors pointers, , since application should plain c++ (no .net or other fancy things), investigating shared pointers , considering using shared pointers everywhere (instead of normal pointers).
i worked out tricks make easier work shared pointers, e.g.: using typedef within class, this:
class x { public: ... typedef std::shared_ptr<x> ptr; };
that way can write x::ptr, easier write "std::shared_ptr" everywhere.
i noticed disadvantages shared pointers:
- everywhere use shared pointer need include
<memory>
- i can't use forward declaration anymore if want use pointer
are there other tricks make shared pointers easier work with?
don't!
the way minimize pointer errors use the right pointer types. , that's types, plural.
shared pointers not silver bullet. become memory leaks when have cyclical references (and if plan use them everywhere, show pretty quickly)
if want error-free c++ applications, have work it. have understand application. have understand ownership semantics of different objects. shared pointers give shared ownership, decent lowest denominator. else can replaced shared ownership , it'll work, sort of.
but default case object owned one other entity. owned function, , should destroyed when function returns, or owned class, or whatever else. often, don't need pointers @ all. object stored value in std::vector
, perhaps. or local variable or class member. if is pointer, it'll better expressed scoped_ptr
or perhaps 1 allows transfer of ownership (unique_ptr
or auto_ptr
).
shared_ptr
might fall when can give no guarantees lifetime or ownership of object. when use that, need use weak_ptr
break cycles.
really, better approach avoid pointers as @ possible. when do need pointer, use 1 has specific ownership semantics possible (prefer scoped_ptr
, doesn't allow transfer of ownership @ all, if need it, fall 1 allows move ownership, such unique_ptr
, , last resort should use shared_ptr
, allows share ownership freely among number of clients.
there's no magic wand can wave make c++ code "just work". way achieve write solid c++ code. , knowing, , using, tools @ disposal, not pretending "hey, shared_ptr
garbage collector, isn't it? can ignore questions of object lifetime or memory leaks if use it".
- Get link
- X
- Other Apps
Comments
Post a Comment