C++ 11 Smart Pointers
What is unique_ptr?
Unique pointer is the simplest efficient default smart point to express the intent of unique ownership of an object at a time that it is efficient in the way that it has no atomic reference counting integer with merely the time overhead at destructor for destroying the owned object and possibly the time overhead at constructor for copying the self-provided non-trivial deleter when compared to raw pointer.
Why use shared_ptrs?
It gives simpler code, and performs a single allocation without explicit new to prevent the two-allocation that may throw exception when a new object is create.
http://stackoverflow.com/questions/22295665/how-much-is-the-overhead-of-smart-pointers-compared-to-normal-pointers-in-c
std::unique_ptr
has memory overhead only if you provide it with some non-trivial deleter.std::shared_ptr
always has memory overhead for reference counter, though it is very small.std::unique_ptr
has time overhead only during constructor (if it has to copy the provided deleter) and during destructor (to destroy the owned object).std::shared_ptr
has time overhead in constructor (to create the reference counter), in destructor (to decrement the reference counter and possibly destroy the object) and in assignment operator (to increment the reference counter).
Note that none of them has time overhead in dereferencing (in getting the reference to owned object), while this operation seems to be the most common for pointers.
To sum up, there is some overhead, but it shouldn't make the code slow unless you continuously create and destroy smart pointers.
沒有留言:
張貼留言