目前我在 C++ 中遇到一些内存管理问题。
void SomeClass::cpy(char** dest, const char* origin)
{
int len = strlen(origin);
char* tmp = new char[len+1];
strncpy(tmp, origin, len);
tmp[len] = '\0';
*dest = tmp;
}
函数调用看起来像这样
for(auto &person : persons)
...
SomeClass::cpy(&(person.name_), new_name);
...
我的问题是删除其范围之外的 tmp 变量。我无法在此范围的末尾删除它,因为我需要它的值。将类析构函数与 delete[] name_;
一起使用似乎违反了内存。
最佳答案
在现代 C++ 中,使用裸指针来拥有对象被认为是一种不好的做法。使用 std::unique_ptr 代替,这将确保在删除内存时释放内存。并且最好从函数返回值而不是使用输出参数。将您的方法签名更改为
std::unique_ptr<char> SomeClass::cpy(const char* origin)
这样 std::unique_ptr
将负责在不再需要时删除内存。
请注意,对于您的特定用例,std::string
可能是更好的选择,因为它是专门为处理字符串而设计的。
关于c++ - 删除其范围之外的已分配(新)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028846/