c++ - To get reference counting, do I have to clutter my APIs with shared_ptr? -


I recently had the following memory bug , which is easy to monitor here, but It can be difficult to find out more complex code:

  square fu: public IFoo {const bar & amp; Bar_; Public: Foo (Constant Bar and Bar): Bar_ (bar) {} zero test () {// login bar_ here}}; Int Baz () {IFoo * foo = NULL; If (whatever) {repeatedly; Foo = new foo (bar); } Other {// create another foo} foo- & gt; exam (); // block fault)  

The bug is that times goes out of the area immediately, is destroyed and then foo-> test () Is used in . One solution is to create bar on a heap, using bar * time = new bar () . However, I do not like to do this because I have to keep the bar * bar pointer at the top level so that I can access it and delete this though at the end, The bar is such a code that is specific to that particular code block (if) {} .

Another solution is boost:: shared_ptr , but I can not write it now:

  if (if any) {boost :: shared_ptr & lt; Bar & gt; Bar (new bar ()); Foo = new foo (* times); }  

Because shared_ptr exits the scope, in addition, destroys the underlying object.

In short, to get rid of this problem, in the member << code> Foo to shared_ptr everywhere , Foo to use constructor etc. To eliminate these problems in general, all my APIs etc. It has to use shared_ptr , which is ugly but, is this the right thing to do? So far, I have used it to create context-calculated objects, but I have kept my API clean from shared_ptr . How do you deal with this problem, once you use shared_ptr you have to use it everywhere ?

(In addition, if you use these reference-count indications, then you have to start worrying about it if you actually have to shared_ptr or weak_ptr etc.).

And, what will I use as the Foo (Constant Bar and Bar) ? Foo (Constant SharePTR & lt; Constellate Bar>) ?

Another option, of course, is to use pimpl to add context coding inside bar and other objects and use their own counters. , But it is also very tedious as the general rule becomes.

Actually I do shared_ptr everywhere ... There are several ways to look at it a little less hassle. For each defined class I use a conference:

class AClass {public: typedef boost :: shared_ptr

makes the code more readable :)

For your specific problem, remember that you can pass the bar by the pointer - remember to allocate you Though on the heap however


Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -