简体   繁体   English

我正在尝试在函数中为新的内存新的堆内存,但是它给出了一个错误

[英]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.

相关问题 findContours给出了内存堆错误 - findContours gives memory heap error 用于堆上内存分配的新运算符 - new operator for memory allocation on heap C ++ - 使用“new”在堆上分配内存 - C++ - Allocating memory on heap using “new” 用C ++中的new分配的堆内存的范围 - Scope of heap memory allocated with new in c++ C++ function 正在泄漏 memory,我是 ZF6F87C9FDCF8B3C9FDCF8B3C3F07F9C3F1 的新手,不确定如何修复 - C++ function is leaking memory, I'm new to C++ and not sure how to fix it 如果我不使用新关键字,我可以有 memory 泄漏吗? - Can I have memory leaks if I'm not using new keyword? Valgrind抱怨内存泄漏,但我正在调用new并删除 - Valgrind complains about a memory leak but I'm calling new and delete 我使用构造函数(使用 memory dinamic char *t = new char [10] t ="test123456";)并在析构函数中删除 [] t; 错误 - i have get error heap error using constructor ( use memory dinamic char *t = new char [10] t ="test123456";) and in distructor delete [] t; error 指针和复发 - 我正在努力节省记忆 - Pointers and recurency - I'm trying to save memory 使用 new 运算符在堆中分配了多少内存? - How much memory is allocated in heap using new operator?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM