c++ - Prevent destruction of self after main? -


i'm writing asynchronous i/o stuff in c++, , need prevent object being destructed until handler asynchronous i/o called. i'm trying use shared_ptr , create object static constructor can sure using reference counting. save in weak_ptr until start asynchronous i/o, when store shared_ptr sure doesn't become invalid during time. finally, reset when callback completes. here's example:

#pragma once  #include <memory> #include <functional>  using namespace std;  class someio {     std::weak_ptr<someio> self;     std::shared_ptr<someio> savingself;      void mycallback() {         // callback stuff here         savingself.reset();     } public:     someio() = delete;     ~someio() {}      static shared_ptr<someio> create() {         auto self = make_shared<someio>();         self->self = self;         return self;     }      void start() {         savingself = self.lock();         //startsomeasyncio(bind(self, someio::mycallback));     } };  int main() {     auto myio = someio::create();      myio->start();      return 0; } 

my question is, going happen after main returns? stay alive until final reference released, or going cause memory leak? if cause memory leak, how handle situation asynchronous i/o can canceled , program can end without memory leak? think shared_ptr protects me memory leaks, i'm not sure situation.

thanks!

in c++ (as opposed java) , program ends whenever main ends. other threads terminated. memory leaks not problem since program ends anyway , memory deallocated.

you can use std::thread std::thread::join prevent program exiting :

int main (void){  std::thread myasynciothread ([]{     auto myio = someio::create();     myio->start(); });  //other things program needs myasynciothread.join(); return 0; }  

you might want interested having thread-pool in program.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -