c++ - 如何删除使用 _strdup() 创建的 const char*
问题描述
我在 Visual Studio 中使用以下代码来存储构造函数参数 char* 并在我的类的解构中将其删除。
#include "pch.h"
#include <iostream>
class A
{
public:
A(const char *fn) {
myChar = _strdup(fn);
}
~A() {
delete[] myChar;
}
char *myChar;
};
int main()
{
A myA("lala");
myA.~A();
_CrtDumpMemoryLeaks(); //leak detector
}
如果我不使用 delete[] myChar,我会造成内存泄漏。如果我使用它,我会在调试时收到这个未知错误。
这样做的正确方法是什么?
更改delete[]
为后free
:
解决方案
这里有几个问题。
你
delete[]
代替free
.strdup
来自 C 库。文档告诉我们如何清理它。微软的类似
_strdup
工作方式相同。您必须阅读您使用的函数的文档,尤其是当您遇到问题时。这就是为什么它在那里。
A
你不应该手动调用析构函数。该对象具有自动存储期限,并将自动销毁。当你出于某种原因自己调用析构函数时,这意味着它最终会被调用两次。这意味着错误的释放调用
delete[] myChar
也将被调用两次,这显然是磨损的。您的对象的复制语义被破坏了。
好的,所以你不要在这里复制它。但是任何管理内存的对象都应该遵循零规则、三规则或五规则。
你过早地检查泄漏。
myA
当你调用时它仍然活着_CrtDumpMemoryLeaks()
,所以它当然会看到它还没有被销毁/释放,并认为这是内存泄漏。您应该在尝试摆脱所有资源之后调用该函数,而不是之前。
这是您直接固定的代码:
#include "pch.h"
#include <iostream>
class A
{
public:
A(const char *fn) {
myChar = _strdup(fn);
}
A(const A& other) {
myChar = _strdup(other.myChar);
}
A& operator=(const A& other) {
if (&other != this) {
free(myChar);
myChar = _strdup(other.myChar);
}
return *this;
}
~A() {
free(myChar);
}
char *myChar;
};
int main()
{
{
A myA("lala");
}
_CrtDumpMemoryLeaks(); //leak detector
}
这就是它应该是的:
#include <string>
#include <utility> // for std::move
#include <crtdbg.h> // for _CrtDumpMemoryLeaks
class A
{
public:
A(std::string str) : m_str(std::move(str)) {}
private:
std::string str;
};
int main()
{
{
A myA("lala");
}
_CrtDumpMemoryLeaks(); // leak detector
}
推荐阅读
- c# - 解决方法 由于目标机器主动拒绝,无法建立连接 127.0.0.1:64527
- scala - 如何以并行方式处理 Dataframe 数据以使用大量参数调用 url
- ios - 音量达到最大值或最小值后,如何在 iOS 中检测音量按钮按下 (+/-)?
- google-apps-script - 仅在 Apps 脚本编辑器中运行脚本时出现错误
- gradle - 我可以简单地使用 maven-publish Gradle 插件上传到 Bintray 还是必须使用 Bintray 插件
- c - 复制/指向 typedef 结构的指针
- swift - 查找选择了哪个标签栏项目
- .net-core - 环境变量配置如何在 dotnet core 中工作?
- python - 类似整数的字符串中的隐藏字符
- c# - 如何在 string.replace 上使用字符串插值