gpt4 book ai didi

c++ - 如何安全地从内存中清除使用 new 关键字创建的对象(具有属性)?

转载 作者:行者123 更新时间:2023-12-04 12:21:35 25 4
gpt4 key购买 nike

据我所知,每个"new"调用都需要对该对象进行相应的“删除”调用。那么这真的正确吗?:

using namespace std;

class Box {
public:
double length;
char letters_in_box[80];
};

int main() {
Box *b = new Box;
b->length = 2.0;
b->letters_in_box = "Hello world";

//Some code with b

delete b;

return 0;
}
与“length”double 和“letters_in_box”数组相关的内存是否被清除?

最佳答案

是的。删除时 b它也会删除 letters_in_box大批。
但是,对于您的 b->letters_in_box = "Hello world";您将收到编译错误:“错误 C3863:数组类型‘char [80]’不可分配”

#include <memory> // For 'memcpy_s' (since C11)

class Box
{
public:
double length;
char letters_in_box[80];
};

int main()
{
Box* b = new Box;

b->length = 2.0;
// b->letters_in_box = "Hello world"; ** Compile Error C3863: array type 'char [80]' is not assignable **
memcpy_s(b->letters_in_box, sizeof(b->letters_in_box), "Hello world", sizeof("Hello world"));

// Some code with b

delete b;
}
现代 C++
new 更好的做法是 智能指针 ,而不是例如您不必在出现异常的情况下删除删除,并且根本不需要:
#include <memory> // For 'std::unique_ptr' and for 'memcpy_s'

class Box
{
public:
double length;
char letters_in_box[80];
};

constexpr char my_text[] = "Hello world";

int main()
{
auto b = std::make_unique<Box>(); // No need to delete

b->length = 2.0;
memcpy_s(b->letters_in_box, sizeof(b->letters_in_box), my_text, sizeof(my_text));

// Some code with b
}
另外,(而不是 C 数组)我更喜欢使用 C++ 数组 :
#include <array>  // For 'std::array'
#include <memory> // For 'std::unique_ptr' and for 'memcpy_s'

class Box
{
public:
double length;
std::array<char, 80> letters_in_box;
};

constexpr char my_text[] = "Hello world";

int main()
{
auto b = std::make_unique<Box>(); // No need to delete

b->length = 2.0;
memcpy_s(&b->letters_in_box, b->letters_in_box.size(), my_text, sizeof(my_text));

//Some code with b
}
——
最后一条评论:无限制使用 char[] , 我会用 std::string反而:
#include <string> // For 'std::string'
#include <memory> // For 'std::unique_ptr'

class Box
{
public:
double length;
std::string letters_in_box;
};

int main()
{
auto b = std::make_unique<Box>(); // No need to delete

b->length = 2.0;
b->letters_in_box = "Hello world";

//Some code with b
}

关于c++ - 如何安全地从内存中清除使用 new 关键字创建的对象(具有属性)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69055519/

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