我是 C++ 的新手,因此对智能指针的概念和用法也是新手。我想为函数中的结构动态分配内存,然后在接收器完成后使用该内存。我希望唯一(非共享)接收器安全地释放内存。类似于以下内容:
typedef struct {
int x;
int y;
} myStruct;
myStruct* initMem(void)
{
myStruct* result = new myStruct();
result->x = 12;
result->y = 14;
return result;
}
int main()
{
cout << ">>>>> Main | STARTED <<<<<" << endl;
myStruct* w = initMem();
cout << w->x << endl;
cout << w->y << endl;
delete w;
return 1;
}
注意:以上只是我想要实现的示例示例。结构比这复杂得多,我必须只使用动态内存分配。
我读到在 C++ 中使用原始指针进行动态内存管理并不好,因为 C++ 有专门用于此的智能指针的概念。你能帮我把上面的逻辑转换成使用智能指针吗?
提前致谢。
最佳答案
没有理由使用指针和动态分配的内存。使用自动存储期限:
myStruct initMem()
{
myStruct result{};
result.x = 12;
result.y = 14;
return result;
}
int main()
{
cout << ">>>>> Main | STARTED <<<<<" << endl;
myStruct w = initMem();
cout << w.x << endl;
cout << w.y << endl;
}
如果您有充分的理由使用动态分配的内存,那么您必须遵守 RAII 原则。标准库中的智能指针就是这样做的:
std::unique_ptr<myStruct> initMem(void)
{
auto result = std::make_unique<myStruct>();
result->x = 12;
result->y = 14;
return result;
}
int main()
{
std::cout << ">>>>> Main | STARTED <<<<<" << std::endl;
std::unique_ptr<myStruct> w = initMem();
std::cout << w->x << std::endl;
std::cout << w->y << std::endl;
}
同样在 C++ 中,您不需要 typedef。实际上不使用它是惯用的:
struct myStruct {
int x;
int y;
};
关于c++ - 从函数安全返回和处理动态分配的内存,C++ 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55359102/