我使用三种内存清除变体.他们都安全吗?我可以得到内存泄漏吗?
I use three variants of memory clearing. Are all of them safe? Can I get memory leaks?
我使用"放置新"来分配我的对象。我使用了三种内存清除的变体。他们都安全吗?我会得到内存泄漏吗?
#include <iostream>
#include <exception>
#include <vector>
using namespace ::std;
class A{
private:
double x;
public:
A() : x(0) { cout << "A class; ptr: " << this << " created." << endl; }
~A() { cout << "A class; ptr: " << this << " destroyed." << endl; }
};
int main(int argc, char* argv[])
try{
// 1. Creating of object in the necessary memory address
static_assert(sizeof(char) == 1, "Unexpected size of char.");
int x = -1; // Variants of memory clearing
while (x < 0 || x > 2) {
cout << "Variant (0,1,2): ";
cin >> x;
}
char* p = new char[sizeof(A)]; // some memory area...
A* a = new(p)A(); // Place my object in the 'p' address.
// Here is my basic work to do...
// Now I must to free my memory:
if(!x){ // First variant
delete a;
}
else if (x == 1){ // Second variant
delete reinterpret_cast<A*>(p);
}
else if (x == 2){ // Third variant
a->~A();
delete[] p;
}
else{
throw runtime_error("Invalid variant!");
}
a = nullptr;
p = nullptr;
cout << endl;
}
catch(exception& e){
cerr << e.what() << endl;
return 1;
}
catch(...){
cerr << "Unknown exception." << endl;
return 2;
}
谢谢。
具有delete[]
和显式析构函数调用的变体是正确的,因为它是你如何分配/构造它的镜像:
char* p = new char[sizeof(A)];
A* a = new(p)A();
...
a->~A();
delete[] p;
但是,如果您没有充分的理由使用新展示位置,请考虑简单明了
:A* a = new A();
...
delete a;
尽管应该为每个new
调用delete
,并且为每个new[]
调用delete[]
,但由于您分配了一个 char
的数组,第二个选项似乎不是很合理,但仍然合法(只要您确定内存块的大小确实等于 sizeof(A)
并且存在该数组中存在 A
类型的有效对象):
char* p = new char[sizeof(A)];
delete reinterpret_cast<A*>(p);
另请注意,以下行完全无用:
static_assert(sizeof(char) == 1, "Unexpected size of char.");
因为它由标准保证,sizeof(char)
总是返回 1。
第三种变体是删除对象并清除已分配内存的正确方法。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏