smart pointer := a wrapper around a normal pointer => scoped pointer: stack allocation
核心
出了scope之后这个smart pointer指向的对象就deleted,即使是new
创建出来在heap上的对象
e.g.
class demo:
class Entity {
public:
Entity() {
std::cout << "Created Entity" << std::endl;
}
~Entity() {
std::cout << "Destroyed Entity" << std::endl;
}
void print() {}
};
到line33会有"Destroyed Entity"打印出来,即使是ScopePtr e = new Entity()
这种在heap上创建对象的写法; 而像line34Entity* e = new Entity()
的写法就不会打印"Destroyed Entity"; 这是因为new
创建对象在heap上,但是ScopePtr e
在stack上;而出了line29-32的scope之后e
就回收了:析构的时候line24: delete m_ptr
unique_ptr<_Tp>
C++本身有一个类型unique_ptr<_Tp>
用法和上面的ScopePtr
相同:因为pointer本身是在stack上面创建的,在出了scope的时候析构会回收这个pointer;所以即使heap创建的对象,在出scope之后这个对象也没了
用法:看line21和22的区别:因为unique_ptr
的constructor是explicit的,所以创建对象的时候只能按照line21的做法,并不能line22那样创建(做了一个implicit conversion)
为了避免UnhandledException:
21行写法 > 22行
问题:不能copy pointer
unique(scoped) pointer: i.e. pointers that cannot be copied, otherwise there will be 2 pointers pointing to the same memory address. When u delete
one of them, the memory allocation gets freed and the pointer left would be pointing to a freed address ❌
e.g.
解决办法:
shared_ptr
和unique_ptr
相比可以copy pointer了,此时会额外allocate memory for a "reference counter" to an object: only when count goes to 0 would the object be destroyed; 由于并不是一个pointer没有就free memory, 所以此时可以copy pointer
#include <memory>
// ...
int main() {
{
std::shared_ptr<Entity> e0;
{
std::shared_ptr<Entity> sharedPtr = std::make_shared<Entity>();
e0 = sharedPtr;
}
}
std::cin.get();
}
可以很清楚看到debug下两个不同shared_ptr在不同scope时候是否还在
weak_ptr
是一个valid的ptr,但是并不增加ref count; 有点类似Java强软弱虚四种引用中的PhantomReference, 只不过这个是跟GC相关的: