在面试中编写两个函数来分配和释放C++中的int数组

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数组的函数?

gsa*_*ras 7

我怀疑有更好的方法

这不是关于更好的方式,而是关于正确性.

使用

delete [] pt;
Run Code Online (Sandbox Code Playgroud)

既然pt 是阵列!


而且,正如thorsan所建议的那样,你设置ptNULL,但在外面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)

灵感来自如何使用新运算符检查内存分配失败?

  • 我认为它不是更多C++ - 就像使用异常本地处理错误一样!虽然我不介意对非本地错误处理使用异常,但使用它们来处理本地错误似乎有点不对.在我所研究的系统上说,内存分配失败是罕见的,并且在整体定位系统根本不存在,即,我认为内存分配失败是真正特殊的,并且不会在本地处理它们,特别是因为很少有无论如何,从本地实际恢复分配失败的方法. (2认同)