mil*_*271 -1 c++ memory pointers try-catch
快速最佳实践问题(注意我不允许在此代码中使用任何智能指针).我的印象是,如果我传递指向函数的指针并发生异常情况,那么如果在被调用函数或首次分配内存的函数中从未删除内存,则内存会泄露.删除catch块中的内存是否安全,还是应该删除调用函数中的内存?
例:
int main() {
object* myPtr = new object(); //dynamic memory on heap
foo(*myPtr); //pass pointer to function foo
return 0;
}
void foo(object &pointer) {
try {
/* do stuff here
with the pointer */
}
catch (const char &e) {
cout<< "An error occured: " << e << endl;
}
catch (...)
cout<< "Caught unknown exception." << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
函数返回后我应该删除指针吗?
int main() {
object* myPtr = new object(); //dynamic memory on heap
foo(*myPtr); //pass pointer to function foo
delete myPtr;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者在try-catch块中?
void foo(object &pointer) {
try {
/* do stuff here
with the pointer */
}
catch (const char &e) {
cout<< "An error occured: " << e << endl;
delete &pointer;
}
catch (...)
cout<< "Caught unknown exception." << endl;
delete &pointer;
}
}
Run Code Online (Sandbox Code Playgroud)
何时删除try-catch块中的指针
别.
main在通话后将其删除foo.
简而言之,在创建它的地方删除它.任何其他东西都会造成混乱的不对称.
我的印象是,如果我传递指向函数的指针并发生异常情况,那么如果永远不会删除内存,则会泄露内存.
不知道你在哪里听到的.算了吧.这是胡说八道.
删除catch块中的内存是否安全,还是应该删除调用函数中的内存?
你可以:
try两个catch块中和两个块末尾的内存try/ catch链之后删除内存两者都完全"安全".
但是,就像我说的那样 -
函数返回后我应该删除指针吗?
对,完全正确.
你有一个缺失*和大写错字:
object* myPtr = new object();
// ^ ^
Run Code Online (Sandbox Code Playgroud)
实际上,带有智能指针的版本可能如下所示:
#include <iostream>
#include <memory>
struct object {};
void foo(object& obj)
{
try {
// do stuff here with the reference (not a pointer)
}
catch (const char* e) {
std::cout << "An error occured: " << e << std::endl;
}
catch (...)
std::cout << "Caught unknown exception." << std::endl;
}
}
int main()
{
auto myPtr = std::make_unique<object>();
foo(*myPtr);
}
Run Code Online (Sandbox Code Playgroud)