Thursday, 15 January 2015

c++ - Where do you call delete if you intended for variables to remain after going out of scope? -



c++ - Where do you call delete if you intended for variables to remain after going out of scope? -

so have

struct info { int x; int y; int z; } void dowork() { info d; d.x = 1; d.y = 2; d.z = 3; pthread_t thrd; pthread_create(&thrd, null, somefunction, (void*)&d); } pthread_mutex_t outputlock = pthread_mutex_initializer;//global scope void* somefunction(void* arg) { info d = (data*)arg; pthread_mutex_lock(&outputlock); std::cout << d->x->d->y+d->z; pthread_mutex_unlock(&outputlock); }

this causes undefined behaviour because dowork() returns argument somefunction() becomes corrupt. prepare do

data* d = new data(); question is, have worry memory leaks since i'm not calling delete? when programme ends, automatically clean memory leaks?

sadly (as far i'm aware) c++11 can't developed on windows 8 (because seems cygwin buggy it).

you this:

struct info { int x; int y; int z; } void dowork() { data* dat = new data; dat->x = 1; dat->y = 2; dat->z = 3; pthread_t thrd; if(pthread_create(&thrd, null, somefunction, (void*)dat) != 0) delete dat; // if thread not created need cleanup here } void* somefunction(void* arg) { data* d = (data*)arg; std::cout << d->x->d->y+d->z; delete d; }

or (better) use smart pointer:

void* somefunction(void* arg) { // c++11 utilize std::unique_ptr std::auto_ptr<data> d(reinterpret_cast<data*>(arg)); // c++ style cast std::cout << d->x->d->y+d->z; }

note: std::auto_ptr superseded std::unique_ptr in c++11

c++ dynamic pthreads new-operator

No comments:

Post a Comment