摘要:
Google C++ Style Guide 要求使用智能指针,明确所有权,提高可读性
Chromium和WebRTC规范禁用了std::shared_ptr,使用std::unique_ptr和rtc::scoped_refptr
一、Google C++ Style Guide
Ownership and Smart Pointers正在上传…重新上传取消https://google.github.io/styleguide/cppguide.html#Ownership_and_Smart_Pointers
Prefer to have single, fixed owners for dynamically allocated objects. Prefer to transfer ownership with smart pointers.
"Ownership" is a bookkeeping technique for managing dynamically allocated memory (and other resources). The owner of a dynamically allocated object is an object or function that is responsible for ensuring that it is deleted when no longer needed. Ownership can sometimes be shared, in which case the last owner is typically responsible for deleting it. Even when ownership is not shared, it can be transferred from one piece of code to another.
"Smart" pointers are classes that act like pointers, e.g., by overloading the * and -> operators. Some smart pointer types can be used to automate ownership bookkeeping, to ensure these responsibilities are met. std::unique_ptr is a smart pointer type which expresses exclusive ownership of a dynamically allocated object; the object is deleted when the std::unique_ptr goes out of scope. It cannot be copied, but can be moved to represent ownership transfer. std::shared_ptr is a smart pointer type that expresses shared ownership of a dynamically allocated object. std::shared_ptrs can be copied; ownership of the object is shared among all copies, and the object is deleted when the last std::shared_ptr is destroyed.
- It's virtually impossible to manage dynamically allocated memory without some sort of ownership logic.