c++ - 函数是否在退出作用域时清除动态内存?

标签 c++ function scope dynamic-memory-allocation

在 C++ 中,函数如何处理在退出函数作用域时动态分配的内存?这段内存是否被清除,或者是否可以传回主 block ?

在上下文中:我有一个函数,我将一个指向 double 的指针传递给它以用作数组。我在函数内动态分配此内存,初始化元素并退出函数。

            void my_func(double* ptr){
            ptr = new double[2];
            ptr[0] = 15; ptr[1] = 10;
            }

然后在主 block 中,我使用新分配的数组。

            int main(){
            double* ptr;
            my_func(ptr);
            cout << ptr[0] + ptr[1] << endl;
            delete[] ptr;
            return 0;

这行得通吗?这种方法是否存在危险/陷阱?

最佳答案

In C++, how does a function treat memory that has been dynamically allocated upon exiting the scope of the function? Is this memory cleared, or can it be passed back into the main block?

在 C++ 中,手动(动态)分配的内存必须手动释放。

In context: I have a function, and I pass it a pointer to double to serve as an array. I dynamically allocate this memory within the function, initialise the elements and the exit the function.

您正在按值获取指针,因此虽然您可以更改指针指向的内容,但不能更改指针本身。这样做只会更改指针的本地拷贝。如果您通过引用获取指针,那么它将起作用:

void my_func(double*& ptr)
{
    ptr = new double[2];
    ptr[0] = 15; ptr[1] = 10;
}

Will this work? Are there dangers/pitfalls associated with this approach?

它大部分都可以工作,但由于相关的陷阱,它不是 C++ 中的方法。最好使用 vector:

std::vector<int> my_func()
{
    std::vector<int> buffer;
    buffer.push_back(15);
    buffer.push_back(10);
    return buffer;
}

关于c++ - 函数是否在退出作用域时清除动态内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10819543/

相关文章:

c++ - VS10/12 中的 Matlab Shared C/C++ lib 抛出很多异常

c++ - OpenGL:在每次迭代中绘制所有场景?

c++ - Q_REQUIRED_RESULT 做什么?

JavaScript。需要在函数内连接两个数组

c - 预处理器如何进行扩展(在包含的头文件中定义宏)

java - 如何在for循环中调用变量?

c++ - if() 语句如何工作

r - 调用函数时设置列名

algorithm - 在 Matlab 中绘制轮廓图需要帮助

javascript - javascript中不同类型的变量声明