[英]Write two functions to allocate and deallocate int array in C++ in the interview
我被要求編寫兩個函數來在C ++中分配和釋放int數組。
int* allocate(int size){
return new int[size];
}
void deallocate(int *pt){
delete pt;
pt = NULL;
}
我想出了上面的兩個功能。
有誰知道有更好的方法來編寫在C ++中分配/解除分配 int數組的函數?
我懷疑有更好的方法
這不是關於更好的方式,而是關於正確性 。
采用
delete [] pt;
因為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;
}
輸出:
gsamaras@pythagoras:~$ g++ -Wall main.cpp
gsamaras@pythagoras:~$ ./a.out
not NULL
為避免這種情況,只需傳遞一個引用 ,如下所示:
void good_deallocate(int*& pt) {
delete [] pt;
pt = NULL;
}
您還可以檢查第一個函數中的分配是否成功,如下所示:
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
}
*/
}
if (int* rc = new(std::nothrow) int[size]) {
return rc;
} else {
cout << "New failed, unable to allocate" << object_name <<
", size needed:" << sizeof( int ) * size << "." << endl;
exit..., return... whatever, just don't use rc.
}
很多評論(這里和其他地方)都是關於“為什么要費心去處理?” 你的程序無法工作,新的/ alloc錯誤不會發生在今天的大型(虛擬)機器上等等。想想一個程序如何檢測到未檢測到的“新”錯誤(或任何錯誤)。 對於“新”,稍后,您通常會看到訪問沖突。 它可能會或可能不會與原始的失敗聲明/變量相關聯。
現在,假裝你是運行這個程序的用戶(可能你沒寫過)。 我經常看到:“訪問違規......核心轉儲”(或類似)? 我想看看:“新的失敗,無法分配'絨毛',大小= 24GB。程序終止。”
在第一個示例中,用戶調用開發人員(凌晨2點,因為這些在最糟糕的時間始終是關鍵錯誤),並且隨后會進行大量的調試工作。 是時候解決了:幾小時? 天? 在第二種情況下,用戶說“24GB?哎呀?檢查輸入 - 哦,哎呀,錯字,我的意思是24KB。讓我解決這個問題。” 解決的時間:分鍾。 沒有電話,沒有挫敗感。
用戶可以理解的 良好診斷可以防止[緊急]電話呼叫! 請注意,例如,即使我正在分配'int',我也包含邏輯對象名稱 ,這有望對用戶有所幫助,並有助於他解決問題。 (嗯,如果需要說的話,在適當的任何級別發出診斷,只需生產並使其有用;值得努力。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.