gpt4 book ai didi

c++ - 如果您打算在超出范围后保留变量,您应该在哪里调用 delete?

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:37 25 4
gpt4 key购买 nike

假设我们有

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() 的参数就会损坏。为了解决这个问题,我这样做了

Data* d = new Data();我的问题是,由于我没有调用 delete,我是否需要担心内存泄漏?当程序结束时,它会自动清除任何内存泄漏吗?

遗憾的是(据我所知)C++11 不能在 Windows 8 上开发(因为 Cygwin 似乎有很多错误)。

最佳答案

你可以这样做:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com