c++ - new 的内存分配

标签 c++ new-operator

我的第一个问题是,当函数结束时,函数中由 new 分配的内存是否会自动删除(释放)。

int* foo()
{
    int *a = new int;  //memory allocated for an int
    *a = 3;
    return (a);
}//function ends -- is memory for integer still allocated.

如果内存在函数结束后自动取消分配,那么我的下一个代码不应该给出一些与访问不属于我的内存相关的错误。

int main()
{
    int *x = foo();
    cout<<*x;
}

最佳答案

不,当然不是。每个 new 都必须与 delete 平衡。 (并且,为了避免任何 future 的疑问,任何 new[] 都必须与 delete[] 保持平衡)。

C++ 中有一些结构可以在容器对象超出范围后有效释放内存。看看 std::shared_ptrstd::unique_ptr

关于c++ - new 的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22911125/

相关文章:

c++ - new 或 new[] 运算符

c++ - 为类的实例提供指向结构的指针

c++ - 我如何查看字符串迭代器的下一个值

c++ - 两次调用 EnumServicesStatusEx() 时,我仍然在 C++ 中得到 EROR_MORE_DATA

c++ - 如何将 ANTLR 4 集成到 C++ 应用程序中

c++ - Visual Studio 包含 Dll 子项目 header 问题

c++ - gcc 奇怪的转换警告(从 ‘A<B>::count_type {aka short unsigned int}’ 转换到 ‘int’ 可能会改变它的值)

scala - 宏采用类主体,消除显式新运算符?

c++ - 使用 init-methods 来避免使用 new 分配对象——这是糟糕的设计吗?

java - 新的 Java 技术 JAXX