How does the destructor know when to activate itself? Can it be relied upon?

Posted by Robert Mason on Stack Overflow See other posts from Stack Overflow or by Robert Mason
Published on 2010-04-08T01:26:31Z Indexed on 2010/04/08 1:33 UTC
Read the original article Hit count: 326

Filed under:
|
|

Say for example i have the following code (pure example):

class a {
   int * p;
public:
   a() {
      p = new int;
   ~a() {
      delete p;
   }
};

a * returnnew() {
   a retval;
   return(&retval);
}

int main() {
   a * foo = returnnew();
   return 0;
}

In returnnew(), would retval be destructed after the return of the function (when retval goes out of scope)? Or would it disable automatic destruction after i returned the address and i would be able to say delete foo; at the end of main()? Or, in a similar vein (pseudocode):

void foo(void* arg) {
   bar = (a*)arg;
   //do stuff
   exit_thread();
}

int main() {
   while(true) {
      a asdf;
      create_thread(foo, (void*)&asdf);
   }
   return 0;
}

where would the destructor go? where would i have to say delete? or is this undefined behavior? Would the only possible solution be to use the STL referenced-counted pointers? how would this be implemented?

Thank you- i've used C++ for a while but never quite been in this type of situation, and don't want to create memory leaks.

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory-leaks