所以说我们有
struct Data
{
int x;
int y;
int z;
}
void doWork()
{
Data 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)
{
Data d = (Data*)arg;
pthread_mutex_lock(&outputLock);
std::cout << d->x->d->y+d->z;
pthread_mutex_unlock(&outputLock);
}
这会导致未定义的行为,因为一旦 doWork() 返回 someFunction() 的参数就会损坏。为了解决这个问题,我这样做
数据* d = new Data();
我的问题是,因为我没有调用 delete
,所以我是否需要担心内存泄漏?当程序结束时,它会自动清理任何内存泄漏吗?
遗憾的是(据我所知)C++11 无法在 Windows 8 上开发(因为 Cygwin 似乎有很多 bug)。
最佳答案
你可以这样做:
struct Data
{
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 to cleanup here
}
void* someFunction(void* arg)
{
Data* d = (Data*)arg;
std::cout << d->x->d->y+d->z;
delete d;
}
或者(更好)使用智能指针:
void* someFunction(void* arg)
{
// From C++11 use std::unique_ptr
std::auto_ptr<Data> d(reinterpret_cast<Data*>(arg)); // C++ style cast
std::cout << d->x->d->y+d->z;
}
注意: std::auto_ptr
在 C++11 中被 std::unique_ptr
取代
关于c++ - 如果您打算让变量在超出范围后保留,您在哪里调用delete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26573073/