gpt4 book ai didi

c++ - 我使用三种内存清除变体。他们都安全吗?我可以得到内存泄漏吗?

转载 作者:行者123 更新时间:2023-11-27 23:12:30 27 4
gpt4 key购买 nike

我使用“placement new”来分配我的对象。我使用三种内存清理变体。他们都安全吗?我会发生内存泄漏吗?

#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。

关于c++ - 我使用三种内存清除变体。他们都安全吗?我可以得到内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19182136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com