[英]I'm trying to new memory new heap memory in a function but it gives an error
Here is my code, I don't know what's wrong with it, why can't I new heap memory? 这是我的代码,我不知道这是怎么回事,为什么我不能新建堆内存?
int*& mergeSort(int* A, int N) {
if (N == 1) {
return new int(A[0]); //error
}
int mid = N / 2;
int* A1 = mergeSort(A, mid);
int* A2 = mergeSort(A + mid, N - mid);
int* B = merge(A1, mid, A2, N - mid);
delete []A1;
delete []A2;
return B;
}
This code fails because it tries to return an lvalue reference to an rvalue. 该代码失败,因为它试图将左值引用返回到右值。 (The result of
new
is an rvalue). (
new
的结果是一个右值)。
The simplest fix is to just have the function return int *
. 最简单的解决方法是使函数return
int *
。
Without this fix, return B;
如果没有此修复程序,则
return B;
also leads to undefined behaviour because you have returned a reference to a local variable. 还会导致未定义的行为,因为您返回了对局部变量的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.