【发布时间】:2021-06-14 22:27:11
【问题描述】:
我想知道是否存在删除指针的模式。更具体地说,当您需要为数据调用某种中间函数时。这是我的想法的一个例子:
int main() {
// some code here
char* return_of_function1 = function1(int_array);
int return_of_function2 = function2(return_of_function1);
delete[] return_of_function1;
// some code here
}
char* function1(int* int_array) {
// some code here
}
int function2(char* char_array) {
// some code here
}
int main() {
// some code here
int return_of_function2 = function2(int_array);
// some code here
}
char* function1(int* int_array) {
// some code here
}
int function2(int* int_array) {
// some code here
return function2(function1(int_array), true);
}
int function2(char* char_array, bool delete_array) {
// some code here
if(delete_array) {
delete[] char_array;
}
return /* return value */;
}
动机是避免对集合属性数据的中间调用。同样,我只是想问一下这是否常用,或者是否是一个好主意。
非常感谢。
【问题讨论】:
-
如果你想要一个模式,RAII 是一个不错的选择。它需要将您的指针包装在一个类中,以便它可以自动为您分配和删除。但是,这很常见,
std::unique_ptr存在。不过,我仍然需要一些时间来阅读 RAII。 -
这些都不是常用的,也不是一个好主意。使用智能指针。
-
如果您想要一个运行时大小的数组,
std::vector是您首选的 RAII 容器。它会为你管理内存。 -
最好的模式是不要使用 new 或 delete ,除非你被学术要求强迫。而是使用标准库中的容器之一或智能指针。
标签: c++ c++11 pointers gcc memory