c++ - 如何安全地从内存中清除使用 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”双精度和“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
比smart pointers更好的做法,例如,在出现异常的情况下,您不必为 delete 操心:
#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
}
推荐阅读
- php - 静态地图上的热图
- javascript - 如何限制用户一起检查特定的复选框?
- python - django urlpattern 路径参数为空('')是什么意思?
- sql - 为什么会出现错误:在预期条件的上下文中指定的非布尔类型的表达式
- flutter - 如何在最新版的cloud firestore Flutter中查询集合组
- java - 如何在java中显示目录的层次结构
- r - 如何优化 R 中低效的递归 for 循环
- python - 使用 For 循环附加一个带有来自另一个类的实例的列表
- graphql - 在 GraphQL 中,运算符 lt 和 gt 是如何工作的?
- magento2 - Magento 2.3 收到数百封付款交易失败的电子邮件