我们如何释放这样分配的内存:A&o=*(新A)
How do we deallocate memory that has been allocated like this: A& o = *(new A)?
请看下面的程序代码。我已经发表了很多评论,以明确我的问题所在。
#include <iostream>
class A {
public:
void test() {
std::cout << "foo" << std::endl;
}
};
int main() {
A& o = *(new A); // The memory for object "o" is allocated on the heap.
o.test(); // This prints out the string "foo" on the screen.
// So far so good.
// But how do I now deallocate the memory used by "o"? Obviously,
// memory has been allocated, but I know of no way to relinquish it
// back to the operating system.
// delete o; // Error: type ‘class A’ argument given to ‘delete’,
// expected pointer
return 0;
}
这行很奇怪
A& o = *(new A);
考虑更改它。我认为仅仅将它声明为指针A* o = new A();
没有任何好处。
如果您想取消分配内存:
delete &o; //Deletes the memory of 'o'
请注意,如果您已将o
定义为
A o = *(new A);
您将没有释放内存的方式,因为o
将是分配的A
的副本(具有全新的地址!)。o
将因此在堆栈上创建,因此delete &o;
将导致未定义的行为。
相关文章:
- 释放错误后堆使用
- G锁定铸造到基础上会释放模拟行为
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 在将变量声明为引用时,堆在释放后使用
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- Python中的for循环与C++有何不同
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- C++双重释放或损坏(out)
- 如何在c++中释放内存
- 使用全局声明的向量时,C++双重释放错误/损坏
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 为什么瓦尔格林德在不释放恶意内存后没有报告任何问题?
- 调用析构函数以释放动态分配的内存
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 如何在向量中释放指针?
- std::unordered_map析构函数不释放内存?
- 在C++中释放内存期间,迭代器与指针有何不同
- 包含矢量指针的结构的内存释放问题
- C++:在被本地字符串捕获后释放或销毁 malloc'd char *?