C++ 智能指針

C++ 智能指針

0. Don’t not use new and delete directly

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.

1. 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));

2. Use tips

Avoid auto_ptr, preger unique_ptr and shared_ptr
Never use smart pointer to non-heap memory
Boost scoped_ptr is equal to unique_ptr

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