C++内存管理与智能指针用法小结

本文探讨了C++中直接使用new/delete操作可能导致的问题,并介绍了C++11标准下智能指针shared_ptr和unique_ptr的使用方法及优势。通过案例展示了如何创建和使用智能指针,以及它们在内存管理上的可靠性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++ 智能指针

1. 不要直接使用new delete操作

If you use new and delete to manage heap memory directly, there is a high possibility to make errors. For example, a block of memory is set in a function, but the delete method is not triggered by an exception, so the problem of memory overflow comes out.
若用new delete操作,由于delete常由于异常未调用,易出现内存泄漏问题。

2. C++ 智能指针(smart pointer)

The C++11 has already defined class shared_ptr, unique_ptr to solve the memory manage. It has a reliable method to delete the memory robustly.
Firstly the smart pointers take ownership of pointer which is produced by new.
The template class has a member named reference count, when the object has disappeared, it will delete the occupied memory in its destructor.
Quotes of C++11 Primer Plus (6th ed)
Create an even smarter pointer that keeps track of how many smart pointers refer to a particular object. This is called reference counting. Assignment, for example, would increase the count by one, and the expiration of a pointer would decrease the count by one. Only when the final pointer expires would delete be invoked. This is the shared_ptr strategy.

  • shared_ptr, unique_ptr用法
std::shared_ptr<double> db_ptr(new double(0.0));
//先声明,后初始化
std::shared_ptr<double> db_ptr;
db_ptr = std::shared_ptr<double>(new double(0.0));
std::shared_ptr<double[]> double_array_ptr(new double(5));
  • shared_ptr 的reference count
std::shared_ptr<std::string> name_ptr[3] = {
 std::shared_ptr<std::string>(new string("China"));
 std::shared_ptr<std::string>(new string("Hack"));
 std::shared_ptr<std::string>(new string("Zhang"));
};
std::shared_ptr<std::string> runner = name_ptr[1];

What’s more, the unique_ptr can be constructed by the temporary returned unqiue_ptr

unique_ptr<int> make_int_ptr(int num) {
  return unique_ptr<int>(new int(num));
}
unique_ptr<int> one_int_ptr(make_int_ptr(0));

3. 使用建议

Avoid auto_ptr, preger unique_ptr and shared_ptr
由于历史原因,auto_ptr十分具有迷惑性,避免使用auto_ptr,而优先选用unique_ptr和shared_ptr。
Never use smart pointer to non-heap memory
对于非栈上存储的数据勿用智能指针。
Boost scoped_ptr is equal to unique_ptr
Boost库中的scoped_ptr等效于std::unique_ptr。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值