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。