123*_*234 2 c++ pointers new-operator dynamic-allocation delete-operator
我被要求编写两个函数来在C++中分配和释放int数组.
int* allocate(int size){
return new int[size];
}
void deallocate(int *pt){
delete pt;
pt = NULL;
}
Run Code Online (Sandbox Code Playgroud)
我想出了上面的两个功能.
有谁知道有更好的方法来编写在C++中分配/解除分配 int数组的函数?
我怀疑有更好的方法
这不是关于更好的方式,而是关于正确性.
使用
delete [] pt;
Run Code Online (Sandbox Code Playgroud)
既然pt
是阵列!
而且,正如thorsan所建议的那样,你设置pt
为NULL
,但在外面deallocate()
看不到,为自己看:
#include <iostream>
using namespace std;
int* allocate(int size) {
return new int[size];
}
void deallocate(int *pt) {
delete [] pt;
pt = NULL;
}
int main() {
int* pt = allocate(5);
deallocate(pt);
cout << (pt == NULL ? "NULL" : "not NULL") << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
gsamaras@pythagoras:~$ g++ -Wall main.cpp
gsamaras@pythagoras:~$ ./a.out
not NULL
Run Code Online (Sandbox Code Playgroud)
为避免这种情况,只需传递一个引用,如下所示:
void good_deallocate(int*& pt) {
delete [] pt;
pt = NULL;
}
Run Code Online (Sandbox Code Playgroud)
您还可以检查第一个函数中的分配是否成功,如下所示:
int* good_allocate(int size) {
try {
return new int[size];
}
catch(std::bad_alloc&) {
cerr << "shit\n";
return NULL;
}
// OR as Dietmar Kühl suggested
/*
if (int* rc = new(std::nothrow) int[size]) {
return rc;
} else {
// handle error
}
*/
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1045 次 |
最近记录: |