在《c++ primer》这本书中看到,两种智能指针管理内存:
shared_ptr<int> sp (new int[10],[](int*p){delete[] p;}):
unique_ptr<int[]> up (new int[10]);
为什么使用shared_ptr
的时候不需要指明int[]
而可以使用int
呢?
大家讲道理2017-04-17 14:54:35
uniqe_ptr<int> up(new int), it will be deleted when deleted later.
uniqe_ptr<int []> up(new int[10]), it will delete [] when deleted later.
Incorrect matching will result in errors.
When the shared_ptr standard was set, no one thought of adding an array specialization to the shared_ptr template. So the implementation of shared_ptr<int[]> calling delete[] does not exist.
shared_ptr<int> sp(new int[10]), when deleting later, delete will be used instead of delete [], which will cause an error.
You must tell shared_ptr how to delete this array, which is the [](int*p){delete[] p;}) at the end. Without this, an error will occur when deleting.
Why wasn’t shared_ptr added when setting the standard? Because they forgot/lazy/no one wrote a proposal, probably like this.
In fact, the unique_ptr and shared_ptr of arrays are not very common. Just use vector directly. .
伊谢尔伦2017-04-17 14:54:35
@hearts has already said it quite comprehensively, let me add one more thing.
In most cases, just use vector
directly. The standard library has been well optimized. But shared_ptr
and unique_ptr
are not useless, especially when it comes to polymorphism. For details, please see the section on object-oriented programming of C++ Primer. shared_ptr
and unique_ptr
are also mentioned before. auto_ptr
are all intended to replace naked pointers [dangerous] . In actual situations, it should be said that shared_ptr
is used less and unique_ptr
is more commonly used.
Of course, both vector
and *_ptr
are all for RAII. This is another interesting topic.
Some simple opinions, please give me some advice.