C++內存管理與智能指針用法小結

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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章