Note that there are some explanatory texts on larger screens.

plurals
  1. POboost::thread and destructor of contained classes
    primarykey
    data
    text
    <p>I would like to understand the behaviour of this code.</p> <pre><code>class Foo { public: Foo(); ~Foo(); void run(); int* get(); private: int *a; }; Foo::Foo() { a=NULL; } void Foo::run() { if ( a==NULL) a = new int[30000]; } int* Foo::get() { return a; } Foo::~Foo() { cout &lt;&lt; "destructor called" &lt;&lt; endl; if ( a!=NULL) delete a; } int main() { Foo *a = new Foo(); boost::thread Foothread( &amp;Foo::run, a); // Some very long computation that sometimes access int *b = a-&gt;get(); cout &lt;&lt; *b &lt;&lt; endl; //Foothread.join(); //delete a; //Foothread.join(); return 0; } </code></pre> <p>This code causes a memory leak of 120000 bytes because variable a is not destructed, so when I explicitly delete it the leak disappers and everything should be ok.</p> <p>Now if I instead of dynamically allocate a, I use static allocation the destructor is called many times!!!</p> <pre><code>int main() { Foo a; boost::thread Foothread( &amp;Foo::run, a); // Some very long computation that sometimes access "a" Foothread.join(); int *b = a.get(); cout &lt;&lt; *b &lt;&lt; endl; return 0; } </code></pre> <p>and the ouput is destructor called, a was 0 Now a is 0 destructor called, a was 0 Now a is 0 destructor called, a was 0 Now a is 0 destructor called, a was 0 Now a is 0 destructor called, a was 0 Now a is 0 destructor called, a was 0 Now a is 0 destructor called, a was 0x75e300 Now a is 0 Segmentation fault</p> <p>The destructor is called N times!!</p> <p>Now I would like to know how to safe allocate and deallocate both class member variable and objects using boost::thread and why the thread destructor doesn't handle the class destructor explicitly.</p> <p>Could someone give me an hint? Should boost::smart_ptr help me? I have to allocate memory with malloc (because I need to use some old C API), how can I do it thread-safely?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload